简体   繁体   English

获取客户的IP地址

[英]Getting a client's IP address

I'm developing an ASP.NET project and I need to determine the client's IP address. 我正在开发一个ASP.NET项目,我需要确定客户端的IP地址。

Currently, the following code on our production server 目前,我们生产服务器上的以下代码

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

returns an IP address that is in the same subnet as the production server's IP address (ie, not solving my problem as it's not the client's IP address). 返回与生产服务器的IP地址在同一子网中的IP地址(即,不能解决我的问题,因为它不是客户端的IP地址)。

However, on our test server, that same line of code returns the client's IP address (the desired result). 但是,在我们的测试服务器上,同一行代码将返回客户端的IP地址(所需结果)。 Anyone have an idea why? 有人知道为什么吗?

I've tried using the above line of code subbing in the following values, all of which return null or an empty string: 我尝试在以下值中使用上面的代码子行,所有值都返回null或空字符串:

"HTTP_X_COMING_FROM"
"HTTP_X_FORWARDED_FOR"
"HTTP_X_FORWARDED"
"HTTP_X_REAL_IP"
"HTTP_VIA"
"HTTP_COMING_FROM"
"HTTP_FORWARDED_FOR"
"HTTP_FORWARDED"
"HTTP_FROM"
"HTTP_PROXY_CONNECTION"
"CLIENT_IP"
"FORWARDED"

As an alternative, I found the following code that does return an array of IP and contains the client's IP address (at index 4): 作为替代,我发现以下代码确实返回IP数组并包含客户端的IP地址(在索引4):

string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string ip = addr[4] != null ? addr[4].ToString() : ""; 

While debugging, I noticed that the IPAddress objects in addr have either (A) Address errors if it's an IPv6 address, or (B) ScopeId errors if it's an IPv4 address. 调试时,我注意到addr中的IPAddress对象要么是(A)如果是IPv6地址,要么有(B)ScopeId错误,如果是IPv4地址,则有错误。 These errors don't seem to be an issue, but I'm not sure if they'll matter once in production. 这些错误似乎不是问题,但我不确定它们在生产后是否会很重要。

Is there a better way to get the client's IP address than the way I have here? 是否有比我在这里获得客户机IP地址更好的方法?

Gets the HttpRequestBase object for the current HTTP request. 获取当前HTTP请求的HttpRequestBase对象。

Request.UserHostAddress

you can get a client's IP address. 您可以获得客户的IP地址。

You can use this function to get ip address. 您可以使用此功能获取IP地址。

    private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {

            var ips= ipList.Split(',');
            return ips[ips.Length - 1];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }

NOTE: HTTP_X_FORWARDED_FOR header may have multiple IP's. 注意:HTTP_X_FORWARDED_FOR标头可能具有多个IP。 The correct IP is the last one. 正确的IP是最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM