When building web apps it is often that you customize content depending on the geographical location of the visitors. The easiest way to achieve this information is that you ask them where they are from, by choosing a country from a long drop-list. The thing is that we developers always want to solve things automatically by code (even when it is not really necessary). I found a excellent free IP to GeoLocation service http://ipinfodb.com, and hacked together a small class that queries the API with the IP address from the visitor.
The code:
using System.Net;
using System.Xml;
namespace Portal.Web.API.Geo
{
public class IPGeoLocation
{
private const string Service = "http://ipinfodb.com/ip_query.php?ip=";
public string City = string.Empty;
public string Country = string.Empty;
public bool FoundGeoData;
public string Ip = string.Empty;
public IPGeoLocation(string ip)
{
var request = (HttpWebRequest) WebRequest.Create(Service + ip);
request.SendChunked = true;
request.Timeout = 5000;
var response = (HttpWebResponse) request.GetResponse();
var xd = new XmlDocument();
xd.Load(response.GetResponseStream());
if (xd.GetElementsByTagName("Status")[0].InnerText.ToLower() == "ok")
{
Country = GetTextValue(xd, "CountryName");
City = GetTextValue(xd, "City");
FoundGeoData = true;
}
else
{
FoundGeoData = false;
}
}
private string GetTextValue(XmlDocument xd, string name)
{
return xd.GetElementsByTagName(name).Count > 0 ? xd.GetElementsByTagName(name)[0].InnerText : string.Empty;
}
}
}
How to use it:
IPGeoLocation ipGeo = new IPGeoLocation(Request.UserHostAddress);
if(ipGeo.FoundGeoData)
{
Response.Write("Country: "+ipGeo.Country+", City: "+ipGeo.City);
}
This example only take care of the city and country, but you can easily extend it to get the long/lat. coordinates to use with Google Maps or similar. Enjoy!