如何在代理后面获取本地IP地址

时间:2015-08-30 14:21:46

标签: c# asp.net-mvc

我正在使用此扩展方法来跟踪用户的IP地址:

public static string GetUser_IP_Address(string input = null)
{
    string visitorsIpAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
         visitorsIpAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (!string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress))
    {
         visitorsIpAddr = HttpContext.Current.Request.UserHostAddress;
    }

    if (input != null)
    {
        return string.Format("Your IP address is {0}.", visitorsIpAddr);
    }
    return visitorsIpAddr;
}

上面的代码为我提供了没有代理的计算机上的实际地址,但是那些有代理设置的人给了我代理服务器的IP地址。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

StackExchange DataExplorer App还使用以下函数确定代理后面的用户的IP地址。你可以看一下。

        /// <summary>
        /// When a client IP can't be determined
        /// </summary>
        public const string UnknownIP = "0.0.0.0"; 

        private static readonly Regex _ipAddress = new Regex(@"\b([0-9]{1,3}\.){3}[0-9]{1,3}$",
                                                         RegexOptions.Compiled | RegexOptions.ExplicitCapture);

       /// <summary>
       /// returns true if this is a private network IP
       /// http://en.wikipedia.org/wiki/Private_network
       /// </summary>
         private static bool IsPrivateIP(string s)
         {
            return (s.StartsWith("192.168.") || s.StartsWith("10.") || s.StartsWith("127.0.0."));
         }
        public static string GetRemoteIP(NameValueCollection ServerVariables)
        {
            string ip = ServerVariables["REMOTE_ADDR"]; // could be a proxy -- beware
            string ipForwarded = ServerVariables["HTTP_X_FORWARDED_FOR"];

            // check if we were forwarded from a proxy
            if (ipForwarded.HasValue())
            {
                ipForwarded = _ipAddress.Match(ipForwarded).Value;
                if (ipForwarded.HasValue() && !IsPrivateIP(ipForwarded))
                    ip = ipForwarded;
            }

            return ip.HasValue() ? ip : UnknownIP;
        }

此处HasValue()是另一个类中定义的扩展名,如下所示:

public static class Extensions
{
    public static bool HasValue(this string s)
    {
        return !string.IsNullOrEmpty(s);
    }
}