如何查找用户的IP地址

问题描述 投票:0回答:1

我需要帮助才能找到正在浏览我网站的用户的IP地址(使用C#代码)。

我对系统IP地址,ISP IP地址,网络地址以及什么是IPV4和IPV6感到困惑。

以下是我从其他来源获得的代码:

protected string GetUserIP()
{
        string userIP = string.Empty;
        HttpContext context = System.Web.HttpContext.Current;

        string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipAddress))
        {
            string[] addresses = ipAddress.Split(',');
            if (addresses.Length != 0)
            {
                userIP = addresses[0];
            }
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            userIP = HttpContext.Current.Request.UserHostAddress;
        }

        return userIP;
}

但在这里,我没有得到预期的结果。

在我的本地主机上测试时,我得到了127.0.0.1

当我将其部署到我的开发服务器并在本地机器中浏览页面时,我得到了不同的地址。

我尝试访问其他机器中的相同URL并且IP地址相同。

我用于在同一网络中访问我的开发服务器部署页面的系统。

那么我的代码返回的网络IP是什么?

因为当我使用ipconfig命令找到我的IP时,它又是一个不同的!

当我使用第三方网站(http://www.whatismyip.com/ip-address-lookup/)检查我的IP时,它会显示我预期的实际IP。如何使用C#代码获取实际IP?

我的最终目标是,获取使用Maxmind City DB浏览我的网站的用户位置详细信息,但为此我需要传递浏览用户的IP。

string ip = GetUserIP();
string db = “GeoIP2-City.mmdb";
var reader = new DatabaseReader(db);
var city = reader.City(ip);
double? lat = city.Location.Latitude;
double? lang = city.Location.Longitude;

对于我从上面的代码得到的IP,当我试图从Maxmind DB获取信息时,我得到了异常(在数据库中找不到IP),但是对于我从“whatismyip”网站获得的IP,我从Maxmind DB获得了详细信息。

希望我的问题很明确。如果有人有任何意见,请告诉我。

谢谢,Sharath

c# asp.net networking ip maxmind
1个回答
0
投票

我想这会有所帮助

public String GetLanIPAddress()
    {
        //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
        //client connecting to a web server through an HTTP proxy or load balancer
        String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (string.IsNullOrEmpty(ip))
        {
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        return ip;
    }
© www.soinside.com 2019 - 2024. All rights reserved.