获取用户的IP地址 [英] Get User's IP Address
问题描述
我怎样才能得到当前访问者的IP地址?
How can I get the current visitors IP address?
推荐答案
编辑:也发现了关于IP相关的HTTP头一个有趣的问题<一href=\"http://stackoverflow.com/questions/527638/getting-the-client-ip-address-remote-addr-http-x-forwarded-for-what-else-could\">here.
also found an interesting question regarding IP-related http headers here.
EDIT2:正如在评论中提到,并在链接我上面提供的 HTTP_X_FORWARDED_FOR
头可以包含由逗号分隔的多个IP-地址。我没遇到过这种情况,但假设需要一些更正我的回答。
As mentioned in comments and in link I provided above, HTTP_X_FORWARDED_FOR
header may contain multiple IP-addresses separated by comma. I didn't face this situation but suppose some corrections to my answer are required.
我用这个code来获得IP地址(如果得到某种原因失败则返回 IPAddress.None
值):
I use this code to get the IP address (it returns IPAddress.None
value if getting failed for some reason):
/// <summary>
/// Gets the IP address of the request.
/// <remarks>
/// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
/// <summary>
/// Gets the IP address of the request.
/// <remarks>
/// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
/// The <see cref="System.Net.IPAddress.None" /> value will be returned if getting is failed.
/// </remarks>
/// </summary>
/// <param name="request">The HTTP request object.</param>
/// <returns></returns>
public static IPAddress GetIp(this HttpRequest request)
{
string ipString;
if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
{
ipString = request.ServerVariables["REMOTE_ADDR"];
}
else
{
ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault();
}
IPAddress result;
if (!IPAddress.TryParse(ipString, out result))
{
result = IPAddress.None;
}
return result;
}
这篇关于获取用户的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!