如何获取当前访问者的IP地址?
解决方法
编辑:还发现一个有趣的问题,关于IP相关的HTTP头
here。
Edit2:如上面提供的注释和链接中所述,HTTP_X_FORWARDED_FOR头可能包含多个以逗号分隔的IP地址。我没有面对这种情况,但假设需要对我的回答进行一些更正。
我使用这个代码获取IP地址(它返回IPAddress.None值如果由于某些原因失败):
/// <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; }