View Light

Determine what IP an incoming request came from

There are many reasons you may need to know/use/track the IP that an incoming request came from. Turns out it's not too hard, but a little sloppy, would think there's a better way to get it than inspecting server variables by name, but here we are.

First off, there are two places it can appear, so they need to be checked in order. The first is "HTTP_X_FORWARDED_FOR", which will be filled in if something (such as a proxy server or a NAT) is forwarding the request from the original requestor. If there's nothing there, then secondly we need to check "REMOTE_ADDR". If there's no forwarder in place, then you get the actual requesting IP - but if there is a forwarder, then REMOTE_ADDR will contain the IP of the forwarder, thus why we have to do this two-step lookup.

Here's some example C# code for doing just that:

public string GetRequestingIp()  
{  
    // First, see if the request came in via a forwarder. (If so, then use the address in this field.)
    var ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
    
    if (string.IsNullOrEmpty(ip)) // We didn't get the request via a forwarder, so get the actual remote address.
    {  
        ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
    }
    
    // Return whichever address was found.
    return ip;  
}  
Rating: (You must be logged in to vote)
Reply
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: http://www.law.cornell.edu/uscode/17/107.shtml . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.