Determine what IP an incoming request came from
Posted: 1/26/2022 10:48:50 AM
By:
Times Read: 891
0 Dislikes: 0
Topic: Programming: .NET Framework

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)