August 22, 2013

How to get Client IP Address using Asp.Net

Client IP address might be sometimes useful depending on the use case. In different projects, the company might decide to release products based on IP address range, etc and it will be useful in those scenarios to get the ip address. However, if the product is a web application and it needs to get location of the user - then, HTML5's geolocation might be a better solution provided. I will discuss about HTML5 geolocation in a different post.

In, the Request object has access to various server variables including HTTP_X_FORWARDED_FOR and REMOTE_ADDR which are two important ones for retrieving client IP address. There is a method in the Request object as well - Request.UserHostAddress() - that can return the client IP. 

The problem with Request.UserHostAddress() is that this method only works if the user is not behind a proxy server. If the user is behind a proxy server, this method returns the IP address of the proxy server. In this situation, the IP address is stored in the server variable - HTTP_X_FORWARDED_FOR. This variable contains a list of comma separated IP addresses in the format client IP, proxy1 IP, proxy2 IP, ... It is important to note that if the original client IP is needed, then we need to get first IP address returned.

If the above variable - HTTP_X_FORWARDED_FOR - returns null, then a different server variable - REMOTE_ADDR - needs to be used to get the IP address. There is no difference between using the method - Request.UserHostAddress() - and the variable - REMOTE_ADDR. Here is a code snippet on how to get the IP address of the client.

Code Snippet
  1. public string GetUserIPAddress()
  2. {
  3.     string ip = null;
  5.     //returns a comma separated IP addresses in the format client, proxy1, proxy2...
  6.     //the IP seen by system is the last proxy IP
  7.     ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  9.     if (ip == null)
  10.     {
  11.         ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  12.         //or use the code below
  13.         //ip = System.Web.HttpContext.Current.Request.UserHostAddress;
  14.     }
  15.     else
  16.     {
  17.         ip = ip.Split(',')[0];
  18.     }
  19.     return ip;
  20. }


Reference: Shahed Kazi at