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);


Article by Asheej T K
Thanks and Regards Asheej T K Dotnet Galaxy

Follow Asheej T K or read 33 articles authored by Asheej T K

Comments

Author: Anil Kumar Pandey16 Dec 2010 Member Level: Diamond   Points : 1

Nice post Asshej..

what does this exactly gives Us the result.

System.Net.Dns.GetHostName();

Author: Pankaj Rajput22 Dec 2010 Member Level: Gold   Points : 0

Hi asheej,

Nice good working code.

System.Net.Dns.GetHostName() ,gives here the Host Machine Name.


Author: Asheej T K22 Dec 2010 Member Level: Gold   Points : 1

Anil,

GetHostName() will return host machine name as pankaj mentioned.
Thanks for the comments.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: