简体   繁体   English

如果服务器在路由器后面,如何获取用户的公共IP?

[英]How to get user's public IP if the server is behind a router?

How can I get the user's public IP if my server is behind a router? 如果我的服务器在路由器后面,如何获取用户的公共IP?

I'm trying: 我尝试着:

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

but all I get is the router gateway. 但我得到的只是路由器网关。

Apparently, REMOTE_ADDR won't work in my case and neither will HTTP_X_FORWARDED_FOR . 显然, REMOTE_ADDR在我的情况下不起作用, HTTP_X_FORWARDED_FORHTTP_X_FORWARDED_FOR

Any ideas on how to get the user's public IP in my case? 在我的情况下,如何获得用户的公共IP有什么想法?

Thanks. 谢谢。

You are trying to deal with IP & Routing at the HTTP level. 您正在尝试在HTTP级别处理IP和路由。

At the Application Layer , the packet has already traversed up the Routing/IP layer and that information has been stripped out. 应用层 ,数据包已经遍历了路由/ IP层,并且该信息已被剥离。

The packet you see at the HTTP level is exactly as sent out by the remote end-point at his Application Layer level, which was devoid of IP information, so looking in the HTTP headers won't help IMHO. 您在HTTP级别看到的数据包与远程端点在其应用层级别发送的数据包完全相同,因为它没有IP信息,因此在HTTP标头中查找将不会帮助恕我直言。

EDIT: As @Marc Gravell said, some Reverse proxies do add this information to HTTP headers. 编辑:正如@Marc Gravell所说,一些反向代理确实将此信息添加到HTTP标头中。 So you should check yours (if you have one configured), if it does that. 因此,如果这样做,则应检查您的(如果已配置)。

This answer lists some other server-variables you could check. 该答案列出了您可以检查的其他一些服务器变量。

The only reliable way is to reach out to some known service on the internet that will tell you what IP it sees your request coming from. 唯一可靠的方法是访问Internet上的某些已知服务,该服务会告诉您看到您的请求来自哪个IP。 Of course, that service has to continue functioning and be reachable or this feature breaks. 当然,该服务必须继续运行并且可以访问,否则此功能将中断。 For example, http://whatismyip.com 例如, http://whatismyip.com

There is no way of getting it. 没有办法。

But, you can find whether the user is opening the page from a local network or from the web. 但是,您可以找到用户是从本地网络还是从网络打开页面。

If the IP is the IP that the router assigns to the requests coming from the web, then it's clear it comes from the web. 如果IP是路由器分配给来自Web的请求的IP,那么很显然它来自Web。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM