简体   繁体   中英

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 :
            HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        return clientIP;
    }

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

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.

Another viable option is:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

Not saying you've got to use this, but the process is much simpler for you with this method.

Previously this was broken in .NET Core RC1 but turns out it's production ready since RC2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM