简体   繁体   English

记录客户端IP地址

[英]Log client IP address

I am trying to log the client IP address for one of the applications that I have build. 我正在尝试为我已构建的应用程序之一记录客户端IP地址。 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. 但是,一旦我们将解决方案部署到具有负载均衡器的生产服务器上,它似乎就记录了负载均衡器的IP地址而不是客户端IP。

I understand that we need to add HTTP_X_FORWARD_FOR header. 我了解我们需要添加HTTP_X_FORWARD_FOR标头。

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. 有时,您的访客位于代理服务器或路由器的后面,而标准Request.UserHostAddress仅捕获代理服务器或路由器的IP地址。 When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR"). 在这种情况下,用户的IP地址随后存储在服务器变量(“ 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. 以前,这在.NET Core RC1中已被破坏,但事实证明自RC2起它就可以投入生产了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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