Introduction
I tried to find a very simple solution for getting the geo-location for a specific IP-address. Most of all, I wanted to avoid tricky string
operations and complexity as shown in articles like this. So I use the XmlReader
now and one of the web-services around.
Using the Code
This class does everything with a few lines:
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace IpLocation
{
public class Response
{
public string Ip, CountryCode, CountryName, RegionCode,
RegionName, City, ZipCode, Latitude, Longitude;
public Response()
{
}
public static Response GetIpLocation(string IpAddress)
{
XmlSerializer serializer = new XmlSerializer(typeof(Response));
XmlReader reader = XmlReader.Create(new StringReader(GetIpData(IpAddress)));
return (Response)serializer.Deserialize(reader);
}
private static string GetIpData(string IpAddress)
{
var web = new WebClient() { Encoding = Encoding.UTF8 };
return web.DownloadString(@"http://freegeoip.net/xml/" + IpAddress);
}
}
}
Then, based on this tiny class, you simply fill myLocation
(X.X.X.X is the IP-address of the location you are looking for) and then use the properties of myLocation
, e.g. CountryName
, City
and all the others:
IpLocation.Response myLocation = IpLocation.Response.GetIpLocation("X.X.X.X");
Points of Interest
I like it, how XmlReader
does everything needed here. This is the result you get from the URL-API:
I was really surprised how elegantly the XmlReader
maps the XML-file with the name and the properties of a defined class, when you precisely use the same names in the class as there are in the XML-tags (see class above). In addition to that XmlReader
's magic effectiveness the method DownloadString
combined with the StringReader
spare us all kinds of file-handling.
History
- 2013-12-08: Posted
- 2013-12-09: Explanation of
XmlReader
added.