views:

437

answers:

6

How do you get the ipaddress and location of every website vistor of your website through Asp.Net?

Thanks

+3  A: 
 string VisitorIPAddress = Request.UserHostAddress.ToString();

and based on the ipaddress you can narrow down the location: find the geographical location of a host

TStamper
+3  A: 

To get the user's IP use:

Request.UserHostAddress

You can use this webservice to get their geographic location. http://iplocationtools.com/ip_location_api.php

Nathan Koop
just FYI, it's a property... not a method :)
Eoin Campbell
thx removed parens
Nathan Koop
This won't work if you're behind a proxy. See my answer.
Anthony
A: 

Well the following property should give you the IP Address of teh client (or the clients proxy server)

Request.UserHostAddress

As for location, you'd need to use some GeoIP/GeoLocation plugin like MaxMind to figure that out.

http://www.maxmind.com/

Eoin Campbell
A: 

To get the IP do:

Request.UserHostAddress

And you can map IP to location using a webservice (slower) or a database (faster) like this: http://ip-to-country.webhosting.info/node/view/5

Infinity
A: 

It's server technology-agnostic, but I'd recommend piggy-backing on Google's AJAX loader: http://code.google.com/apis/ajax/documentation/#ClientLocation

It's in Javascript and will even give you the person's city/state/country (well, it takes a guess based on IP address). Post it back to the server and it's available to you in ASP.NET or whatever.

tlianza
+1  A: 

Request.UserHostAddress won’t work if you're behind a proxy. Use this code:

public static String GetIPAddress()
{
    String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(ip))
        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    else
        ip = ip.Split(',')[0];

    return ip;
}

Note that HTTP_X_FORWARDED_FOR should be used BUT as it can return multiple IP addresses separated by a comma you need to use the Split function. See this page for more info.

Anthony