How to get client "IP Address" using Asp.net /C#

I have found that in various forum newbie are very frequently asked this type of question how to get client IP or get mac address or country. So that I would like to share this for that user. Though its very simple but helpful.

Tip:1
To get the client IP you can use the following function
    string sClientIp=Request.UserHostAddress();
or
    string strHostName = System.Net.Dns.GetHostName();
        string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
 
Tip:2:To avoid Proxy IP:

To get the IP address of the machine and not the proxy use the following code
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 This will returns the client ip in string format.

Code:
C#
    string ip;
    
    ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR");
    if(ip==string.Empty)
    {
      ip=Request.ServerVariables("REMOTE_ADDR");
    }

REMOTE_ADDR does not always provide the users IP but rather the ISPs' IP address so first test HTTP_X_FORWARDED_FOR as this one is the real user IP.

Another important note to this the HTTP_X_FORWARDED_FOR may contain an array of IP, this can happen if you connect through a proxy.What also happens when this happens is that the REMOTE_ADDR may contain the proxy IP. To avoid this problem you can parse the HTTP_X_FORWARDED_FOR for first entery IP.

Code:
C#
    string ip;
    ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR") ;
       if (!string.IsNullOrEmpty(ip))
         {
          string[] ipRange = ip.Split(',');
          string trueIP = ipRange[0].Trim();
         }
       else
        {
         ip=Request.ServerVariables("REMOTE_ADDR");
        }

Hope that it may helpful for the newbie.Please inform me if anything wrong in this article.

Comments

sayed said…
nice....

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript