I have this extension method to get a user's IP in both ASP.NET MVC and ASP.NET WebAPI projects:
public static string GetUserHostAddress(this HttpRequestMessage request) {
if (request == null)
return string.Empty;
HttpRequestBase httpRequest = null;
if (request.Properties.ContainsKey("MS_HttpContext"))
httpRequest = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request;
else if (HttpContext.Current != null)
httpRequest = new HttpRequestWrapper(HttpContext.Current.Request);
if (httpRequest == null) {
if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) {
var prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
return string.Empty;
}
var ip = httpRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrWhiteSpace(ip)) {
ip = ip.Split(':')[0];
} else {
ip = httpRequest.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrWhiteSpace(ip))
ip = httpRequest.UserHostAddress;
}
ip = ip ?? string.Empty;
return ip;
}
The problem is in this part: ip = ip.Split(':')[0];
! In many posts (in blogs, or in SO), I see I should use the first item in this array; and, in many others posts, they said use the last item in array: ip = ip.Split(':').Last();
So, the question is: which group are right? The first one, or the last one?