记录客户端IP地址 [英] Log client IP address

查看:109
本文介绍了记录客户端IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我已构建的应用程序之一记录客户端IP地址.它可以在开发服务器上正常运行.但是,一旦我们将解决方案部署到具有负载均衡器的生产服务器上,它似乎就记录了负载均衡器的IP地址,而不是客户端IP.

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.

我了解我们需要添加HTTP_X_FORWARD_FOR标头.

I understand that we need to add HTTP_X_FORWARD_FOR header.

这是我的代码:

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

推荐答案

有时,您的访问者位于代理服务器或路由器的后面,而标准Request.UserHostAddress仅捕获代理服务器或路由器的IP地址.在这种情况下,用户的IP地址然后存储在服务器变量("HTTP_X_FORWARDED_FOR")中.

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.

这篇关于记录客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆