【发布时间】:2010-12-26 19:18:22
【问题描述】:
我想获取在我的网站上注册的人的 IP 地址。如何在 ASPNET 中执行此操作。我使用了以下代码,但是它没有得到正确的 IP 地址
string ipaddress = Request.UserHostAddress;
【问题讨论】:
我想获取在我的网站上注册的人的 IP 地址。如何在 ASPNET 中执行此操作。我使用了以下代码,但是它没有得到正确的 IP 地址
string ipaddress = Request.UserHostAddress;
【问题讨论】:
在 MVC 6 中,您可以通过以下方式检索 IP 地址:
HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString()
【讨论】:
Request 来获取Context 呢?这应该只是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"];
}
【讨论】:
le 变量 - 我猜你想在下一行使用它而不是 0
您可以使用此方法获取客户端机器的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;
}
【讨论】:
X-Forwarded-For 可以包含多个 IP 地址。
在您将 IP 地址用于安全性的情况下,您应该了解您的基础架构。
如果您在 Web 服务器和设置标头的客户端之间使用代理,您应该能够信任最后一个地址。然后,您使用像 Muhammed 建议的代码进行更新,以始终从转发标头中获取最后一个 IP 地址(参见下面的代码)
如果您不使用代理,请注意 X-Forwarded-For 标头很容易被欺骗。我建议你忽略它,除非你有明确的理由不这样做。
我将 Muhammed Akhtar 的代码更新如下,供大家选择:
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;
}
Wikipedia article 这个Wikipedia article 更彻底地解释了风险。
【讨论】:
应该使用HTTP_X_FORWARDED_FOR,但它可以返回多个用逗号分隔的IP地址。见this page。
所以你应该经常检查它。我个人使用Split函数。
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 = (HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? "").Split(',').Last().Trim();
如果客户端通过透明的非匿名代理连接,您可以从以下位置获取他们的地址:
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
如果无法通过这种方式获取 IP,则返回 null 或“未知”。
Request.ServerVariables["REMOTE_ADDR"] 应该与Request.UserHostAddress 相同,如果请求不是来自非匿名代理,则可以使用其中任何一个。
但是,如果请求来自匿名代理,则无法直接获取客户端的 IP。这就是他们将这些代理称为匿名的原因。
【讨论】: