Libin Joseph Libin Joseph - 10 months ago 75
HTTP Question

Log client IP address

I am trying to log the client IP address for one of the applications that I have build. It works OK on the dev server. But as soon as we deploy the solution on to the production server, which has load balancer,it seems to log the Load Balancer's IP address rather than the client IP.

I understand that we need to add HTTP_X_FORWARD_FOR header.

This is my code :

private static string GetCurrentIp()
String clientIP =
(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null) ?
HttpContext.Current.Request.UserHostAddress :

return clientIP;

Appreciate if someone could help me identify the mistake that I have done

Answer Source

Sometimes your visitors are behind either a proxy server or a router and the standard Request.UserHostAddress only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").

protected string GetIPAddress()
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
            return addresses[0];

    return context.Request.ServerVariables["REMOTE_ADDR"];

above code helps you to make it working.