How to obtain IP Address of a Client

by Jig 22. June 2010 11:25

I have been working on this since last few days so thought of making a note of it. It may be useful for many others as well who are in same boat. One of our application would like to know the IP address of user/visitor. It is used for authentication based on IP addresses but I am not going in details regarding that functionality in this blog. User may or may not come through proxy server. Here, I would like to provide a general method to fetch client's IP address through ASP.Net and give an explanation on the result in terms of different hardware conditions.

 

[C# Code]


private string getIPAddress()

    {

        string strIpAddress;

        strIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (string.IsNullOrEmpty(strIpAddress))

            strIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        return strIpAddress;

    }

 

In above sample code, HTTP_X_FORWARDED_FOR is used to detect if client is using proxy server or not. If client uses proxy server, then the above method will try to obtain IP address behind the proxy server. In many situations, the IP addresses we get are probably the addresses of proxy server.

 

1. Not Use Any Proxy Server:

REMOTE_ADDR = IP address of client
HTTP_X_FORWARED_FOR = No value of no display

 

2. Use Transparent Proxies:

REMOTE_ADDR = IP address of proxy server
HTTP_X_FORWARED_FOR = Real IP address of client

 

3. User Normal Anonymous Proxies:

REMOTE_ADDR = IP address of proxy server
HTTP_X_FORWARED_FOR = IP address of proxy server

 

Another important fact that may affect the result of above code is the configuration of router. If the router of local network enables NAT (network address translation), then the IP address obtained is the address used by the router or load balancer to access external network. 

Before using above co de, it is necessary to consider the real product environment and then use it accordingly.

 

Happy coding!

Hi, I'm Jignesh

My name is Jignesh Panchal and I am a Sr Software Engineer, UI Designer and system architect. I follow and practice Software Craftsmanship principals, clean code, lean startup methodology.

 

Besides this, in my free time I love to play tennis, cricket, PC and PS3\Xbox One games, dig in web development and design. Hardware hacking using Raspberry Pi, Arduino.

Page List