记录客户端IP地址(Log client IP address)

编程入门 行业动态 更新时间:2024-10-20 13:47:00
记录客户端IP地址(Log client IP address)

我正在尝试记录我构建的其中一个应用程序的客户端IP地址。 它在开发服务器上运行正常。 但是,只要我们将解决方案部署到具有负载均衡器的生产服务器上,它似乎就会记录Load Balancer的IP地址而不是客户端IP。

我知道我们需要添加HTTP_X_FORWARD_FOR标头。

这是我的代码:

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; }

感谢有人能帮助我找出我所犯的错误

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

最满意答案

有时您的访问者位于代理服务器或路由器后面,标准Request.UserHostAddress仅捕获代理服务器或路由器的IP地址。 在这种情况下,用户的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"]; }

上面的代码可以帮助你使它工作。

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.

更多推荐

本文发布于:2023-07-22 09:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   地址   IP   address   Log

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!