Friday, December 31, 2010

How to get Client IP address using ASP.NET

This is one of the common query asked in many forums and I saw people giving different answer for this query. So I thought I will clarify this here.

I will start with the most common answer we can see for this query,

 string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  
 Response.Write("Client machine IP:-"+ipAddress);
  


I wonder people are really checking this code and the output of this code if client is using proxy!!!!
Above code will always give 127.0.0.1 that is the default localhost IP Address.
If you are using proxy then above code will not work.
What we have to do in that case is get the machine name first and find the IP address by passing the machine name like below,

 string strMachineName = System.Net.Dns.GetHostName();
  
 string IPAddress = System.Net.Dns.GetHostAddresses(strMachineName).GetValue(0).ToString();    
  
 Response.Write("Client machine Name"+ strMachineName); 
  
 Response.Write("Client machine IP Address"+ IPAddress);
  

1 comment:

Anonymous said...

Dear Mrs. Asheej,
I am currently working on an ASP.NET project and I am looking for help.
Would it please be possible to talk a little bit via Yahoo Messenger or Skype?

If possible, I would like to be contacted at gigibagigi72[at]yahoo[dot]com

Regards,
Matteo