2013-01-16 206 views
0

我从ASP.NET获取客户端IP地址。但某些客户端IP地址收到127.0.0.1。 什么是问题。如何获得有效的客户端IP地址?错误的客户端IP地址

我正在使用此代码:

public static string GetIP() 
{ 
    string clientIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
    if (!string.IsNullOrEmpty(clientIp)) 
    { 
     string[] forwardedIps = clientIp.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
     clientIp = forwardedIps[forwardedIps.Length - 1]; 
    } 

    if (string.IsNullOrEmpty(clientIp)) 
     clientIp = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]; 
    if (string.IsNullOrEmpty(clientIp)) 
     clientIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 

    return clientIp.ToString(); 
} 
+0

127.0.0.1是本地主机地址,我想你是从它托管的同一台计算机连接到页面? –

+0

只是一个猜测?但可能是代理问题。看看http://stackoverflow.com/questions/7445592/what-is-the-difference-between-http-client-ip-and-http-x-forwarded-for – sircapsalot

+0

sircapsolat,我想是的。但我找不到如何解决。 –

回答

1

127.0.0.1为localhost,即在相同的机器发出请求作为承载它。

我的猜测是,你所看到的事实上是你自己的测试或调试?

我会考虑Request.IsLocal()作为一个很好的方法来找出。

+0

攻击我的服务器这个IP。它每秒创建100-200次会话。 –