HttpContext.Current.Request.UserHostAddress为null

Sex*_*yMF 11 c# ip-address

  1. 在我的Dev Machine中HttpContext.Current.Request.UserHostAddress为null.为什么?我怎么能打开它?
  2. 如果是代理客户端,如何获取Ips列表?

使用ASP.net 4 window7的WCF服务.

谢谢

Vir*_*iya 7

为了避免这个问题,你可以解析最后一个entery IP的HTTP_X_FORWARDED_FOR.

ip=Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ;
if (!string.IsNullOrEmpty(ip))
{
   string[] ipRange = ip.Split(',');
   int le = ipRange.Length - 1;
   string trueIP = ipRange[le];
}
else
{
   ip=Request.ServerVariables["REMOTE_ADDR"];
}
Run Code Online (Sandbox Code Playgroud)

希望这会对你有所帮助

  • 只是关于"Viral Sarvaiya"的回答.根据[维基百科](http://en.wikipedia.org/wiki/X-Forwarded-For)和[亚马逊](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html )X-Forwarded-For标头具有以下格式:> X-Forwarded-For:client,proxy1,proxy2这意味着你应该使用`ipRange`中的第一个字符串,而不是最后一个字符串. (3认同)