Get user IP address

Well, yes, it looks like trivial but it isn’t. Many a times we need to get the IP address of the user. There are a handful of suggestions to do this. I discuss the methods and the short comings in them.

1. REMOTE_ADDR

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];

This method fails when the user’s request travels through a Proxy server. The IP address in this case will be of the proxy.

2. HTTP_X_FORWARDED_FOR

string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Generally method 1 is overcome by using HTTP_X_FORWARDED_FOR server variable. This method returns the user address. Well this method fails when the user request does not come through a proxy.

3. REMOTE_ADDR and HTTP_X_FORWARDED_FOR

string ipAddress =  Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
    ipAddress = Request.ServerVariables["REMOTE_ADDR"];

Using the combination of method 1 and 2 we come to method 3. Do you think this is the solution? No. This ain’t too. The reason being, sometimes the requests passes through multiple Proxy servers. In this case HTTP_X_FORWARDED_FOR contains comma separated values of the various proxy servers through which the request passes. So you actually do not have one IP address but multiple ones.

4. REMOTE_ADDR and HTTP_X_FORWARDED_FOR and some processing

string ipAddress =  Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
    ipAddress = Request.ServerVariables["REMOTE_ADDR"];

int index = -1;
if ((index = ipAddress.IndexOf(",")) > -1)
{
    ipAddress = ipAddress.Substring(0, index);
}

The final solution we come to is, use method 3 but check if there is comma separated values. If there is then we take the first IP address which will be the IP address of the user.

I have formatted this into a method which can be reused,

public static class Utility
{
    public static string GetIP(NameValueCollection nameValueCollection)
    {
        string result = string.Empty;

        if (nameValueCollection == null || nameValueCollection.Count < 1)
            return result;

        result = nameValueCollection["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(result))
            return nameValueCollection["REMOTE_ADDR"];

        int index = -1;
        if ((index = result.IndexOf(",")) > -1)
        {
            result = result.Substring(0, index);
        }

        return result;
    }
}

Request.ServerVariables is a NameValueCollection. To use the above method you will have to pass in Request.ServerVariables as a parameter. Like this,

string ipAddress = Utility.GetIP(Request.ServerVariables);

An important inclusion is that this method works for Transparent proxies. There is no way (what I know) to detect the real IP address of a user for a Anonymous/Distorting Proxy.

Have fun.

Tags: ,

Leave a Reply