Ahsan's Experience

sharing experiences in .net ………

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.
More more info pls visit: http://aspboss.blogspot.com/

May 6, 2010 Posted by | asp.net, C#, Web | , , , | 2 Comments