Getting user IP Address using C#

Tracking the users hit to the web applications is required to know the users demography. Also it is a necessary in securing our applications by restricting the odd IP address from the application server.

In most of the scenario’s the user IP address will be tracked with the last gate way by which request was forwarded. Here we will discuss about the IP Address tracking of user with the Proxy, gateway and user machine’s IP.

Example
  1. private static string Fetch_UserIP()   
  2. {  
  3.     string VisitorsIPAddress = string.Empty;  
  4.     try  
  5.     {  
  6.         if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)   
  7.         {  
  8.             VisitorsIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  
  9.         }   
  10.         else if (HttpContext.Current.Request.UserHostAddress.Length != 0)   
  11.         {  
  12.             VisitorsIPAddress = HttpContext.Current.Request.UserHostAddress;  
  13.         }  
  14.     } catch (Exception ex)   
  15.     {  
  16.   
  17.         //Handle Exceptions  
  18.     }  
  19.     return VisitorsIPAddress;  
  20. }  
The above can be used to fetch the Users IP and all the gateway’s IP address.
  1. HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]  
will have all the details with comma separated string. The first IP is the users machine IP . The HttpContext.Current.Request.UserHostAddress will be used, whenever the
  1. HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]  
Doesn’t have the value.
Ebook Download
View all
Learn
View all