2015-08-30 65 views
0

我使用這個擴展方法來跟蹤用戶的IP地址: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地址。
有什麼想法?

回答

2

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