0

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?

amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • According to the specification there isn't a colon in the `HTTP_X_FORWARDED_FOR` header. Thus you would always get the first value which also happens to be the correct one. – jgauffin Oct 19 '15 at 15:00
  • You can read more about the header here: https://en.wikipedia.org/wiki/X-Forwarded-For – jgauffin Oct 19 '15 at 15:02

0 Answers0