ASP Snippets

Categories






Alerts

Free Alerts

Your email will always be
private and will not be shared.




Follow us on twitter.




Zoom In | Zoom Out


Author is awarded Most Valuable Professional award by Microsoft ASP/ASP.Net

How to get IP Address of Visitor's Machine in ASP.Net

Author:Mudassar Khan

Many times there’s a query to get the IP Address of the client machine from which the user visited the website. Hence I decided to post this snippet.

The following snippet gets the IP address of the machine from which the client visited the website.

 

C#

string ipaddress;

ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (ipaddress == "" || ipaddress == null)

    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

 

VB.Net

Dim ipaddress As String

ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")

If ipaddress = "" Or ipaddress Is Nothing Then

   ipaddress = Request.ServerVariables("REMOTE_ADDR")

End If

 

When users are behind any proxies or routers the REMOTE_ADDR returns the IP Address of the router and not the client user’s machine. Hence first we need to check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server his machine’s IP Address the Proxy Server’s IP Address is appended to the client machine’s IP Address. If there are multiple proxy servers the IP Addresses of all of them are appended to the client machine IP Address.

Hence we need to first check HTTP_X_FORWARDED_FOR and then REMOTE_ADDR.




Note: While running this application on your machine it will show IP Address 127.0.0.1 since your client and server is the same machine. So no need to worry deploy it on server you’ll see the results

You can download the sample source here.

IpAddress.zip (2.59 kb)

Posted: Apr 11 2009, 03:28 by Mudassar Khan | Comments (12) RSS comment feed |
Filed under: ASP.Net | C# | VB.Net

Views: 6388
Page copy protected against web site content infringement by Copyscape


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share





Comments

Add comment


 

biuquote
  • Comment
  • Preview
Loading




0  +  0  =   










Community News





Web Hosting SpotLight


Consulting


For consulting and work related queries click here.



Advertise


Advertise with us. For more details click here.


Suggestions


Please provide your valuable suggesstions here.

This Site is hosted on

Lunarpages.com Web Hosting