In Tip of the Day #9 I showed you how you can obtain your clients IP addresses through either server side script or a simple web service call. In this tip I will show you how to take that IP address to determine the geographical location of the user that has that IP.
To accomplish this we simply make a WebClient call to a public based web service that will look up the IP address and return the geographical information that is contained in their database.
An example free web service that provides this data is http://ipinfodb.com. The url we pass is in this format http://ipinfodb.com/ip_query.php?ip=YOURIP. Replace YOURIP with your actually IP, copy and paste this URL into the IE address bar and you will see your results.
To do this through Silverlight I set up a WebClient call with the url in the format I showed you above:
string url = "http://ipinfodb.com/ip_query.php?ip={0}";
string reqUrl = string.Format(url, ipAddress);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloadInfoCompleted);
client.DownloadStringAsync(new Uri(reqUrl), null);
The method downloadInfoCompleted() is called when the WebClient query has completed. Using XML Linq I extract the data I want from the results as seen here:
void downloadInfoCompleted(object sender, DownloadStringCompletedEventArgs e)
{
XDocument xml = XDocument.Parse(e.Result);
XElement ip = xml.Element("Response").Element("Ip");
XElement countryCode = xml.Element("Response").Element("CountryCode");
XElement countryName = xml.Element("Response").Element("CountryName");
XElement regionCode = xml.Element("Response").Element("RegionCode");
XElement regionName = xml.Element("Response").Element("RegionName");
XElement city = xml.Element("Response").Element("City");
XElement postalCode = xml.Element("Response").Element("ZipPostalCode");
XElement timeZone = xml.Element("Response").Element("Timezone");
XElement gmtOffset = xml.Element("Response").Element("Gmtoffset");
XElement dstOffset = xml.Element("Response").Element("Dstoffset");
XElement latitude = xml.Element("Response").Element("Latitude");
XElement longitude = xml.Element("Response").Element("Longitude");
}
Any number of these values could return null. To get the actual value I first check if it is null else I obtain the data from XElement.Value as seen here:
if(null != ip)
IPTB.Text = "Your IP = "+ip.Value.ToString();
Source: Tip10_GeoLocation
Demo:
[silverlight: Tip10_GeoLocation.xap]
Thank you,
–Mike






