如何获取IP地址?

我想要获得在我的网站注册的IP地址。 如何在ASPNET中做到这一点。 我使用了下面的代码,但是没有得到正确的IP地址

string ipaddress = Request.UserHostAddress; 

您可以使用此方法获取客户机的IP地址。

 public static String GetIP() { String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } return ip; } 

应该使用HTTP_X_FORWARDED_FOR,但它可以返回多个由逗号分隔的IP地址。 看到这个页面 。

所以你应该经常检查它。 我个人使用分割function。

 public static String GetIPAddress() { String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; else ip = ip.Split(',')[0]; return ip; } 

在您使用IP地址进行安全保护的情况下,您应该了解您的基础设施。

如果您在Web服务器和设置标题的客户端之间使用代理,则应该可以信任最后一个地址。 然后,你使用像Muhammedbuild议更新的代码,总是从前向头获得最后一个IP地址(见下面的代码)

如果您不使用代理,请注意X-Forwarded-For标头很容易被欺骗。 除非你有明确的理由,否则我build议你忽略它。

我更新了穆罕默德·阿赫塔尔的代码,如下所示,让你select:

 public string GetIP(bool CheckForward = false) { string ip = null; if (CheckForward) { ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } else { // Using X-Forwarded-For last address ip = ip.Split(',') .Last() .Trim(); } return ip; } 

这篇维基百科文章更彻底地解释了风险。

如果客户端通过透明非匿名代理进行连接,则可以通过以下方式获取他们的地址:

 Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 

如果无法获得IP,可以返回null或“unknown”。

Request.ServerVariables["REMOTE_ADDR"]应该与Request.UserHostAddress相同,如果请求不是来自非匿名代理,则可以使用其中的任何一个。

但是,如果请求来自匿名代理,则无法直接获取客户端的IP。 这就是为什么他们把这些代理匿名

在MVC 6中,您以这种方式检索IP地址:

 HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString() 
 string result = string.Empty; string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ip)) { string[] ipRange = ip.Split(','); int le = ipRange.Length - 1; result = ipRange[0]; } else { result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }