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

北城余情 提交于 2019-12-21 17:50:02

问题


How can I get the user's public IP if my server is behind a router?

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.

Any ideas on how to get the user's public IP in my case?

Thanks.


回答1:


You are trying to deal with IP & Routing at the HTTP level.

At the Application Layer, the packet has already traversed up the Routing/IP layer and that information has been stripped out.

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.

EDIT: As @Marc Gravell said, some Reverse proxies do add this information to HTTP headers. So you should check yours (if you have one configured), if it does that.

This answer lists some other server-variables you could check.




回答2:


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. Of course, that service has to continue functioning and be reachable or this feature breaks. For example, http://whatismyip.com




回答3:


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.



来源:https://stackoverflow.com/questions/13177134/how-to-get-users-public-ip-if-the-server-is-behind-a-router

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!