如何找到用户的IP地址

本文关键字:IP 地址 用户 何找 | 更新日期: 2023-09-27 18:11:19

我需要帮助找到用户的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

如何找到用户的IP地址

我想这会有帮助

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;
    }