使用C#的客户端IP

Nit*_*esh 3 c# asp.net ip

如何在C#中获取客户端机器的IP地址.我想为我的在线应用程序保留一个日志寄存器,并保留日志系统的IP地址,我想获取客户端的IP地址....

预谢谢...

Cha*_*ndu 8

    String clientIP = 
(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]==null)?
HttpContext.Current.Request.UserHostAddress:
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Run Code Online (Sandbox Code Playgroud)

  • String clientIP = HttpContext.Current.Request.ServerVariables ["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.UserHostAddress是不是更具可读性?+1代理检查 (3认同)

Mat*_*hen 6

HttpContext.Current.Request.UserHostAddress
Run Code Online (Sandbox Code Playgroud)

这不会尝试考虑代理.为此,你可以使用Request.ServerVariables["HTTP_X_FORWARDED_FOR"].但是,请确保你不会盲目相信,因为它可能是伪造的.最好保留您信任的IP白名单.

  • @Nithesh,它正在发挥作用.*是*实际连接到服务器的IP.这意味着您的服务器位于`localhost` (2认同)