Jonas Stawski

Everything .NET and More

Sample Code for Getting the User Location based on the IP Address

Yesterday I introduced a free service to get the location of the IP Address. If you haven’t read it, go on read that first (it’s very short, I promise). So here I am today, showing you my small .NET API to abstract the XML returned by the service.

First we need an object to hold the data. I called it UserLocation.

   1: public class UserLocation
   2: {
   3:     public string City { get; set; }
   4:     public string Country { get; set; }
   5:     public string CountryAbbrev { get; set; }
   6:     public double Latitude { get; set; }
   7:     public double Longitude { get; set; }
   8: }

Then I created a helper class to retrieve the info. I called it GeoLocation:

   1: public class GeoLocation
   2: {
   3:     //you might want to retrieve this from a config file
   4:     private static string ServiceAddress = "http://api.hostip.info/?ip={0}";
   5:     public static UserLocation Locate(string ipAddress)
   6:     {
   7:         string url = String.Format(ServiceAddress, ipAddress);
   8:         //Get the XML from the request
   9:         XmlDocument xml = GetXml(url);
  10:         //Parse the XML into a UserLocation
  11:         return ParseUserLocation(xml);
  12:     }
  13:  
  14:     private static XmlDocument GetXml(string url)
  15:     {
  16:         HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
  17:         myReq.Method = "GET";
  18:         HttpWebResponse myResp = null;
  19:         XmlDocument xml = null;
  20:         try
  21:         {
  22:             myResp = (HttpWebResponse)myReq.GetResponse();
  23:             if (myResp != null && myResp.StatusCode == HttpStatusCode.OK)
  24:             {
  25:                 Stream dataStream = myResp.GetResponseStream();
  26:                 StreamReader reader = new StreamReader(dataStream);
  27:                 xml = new XmlDocument();
  28:                 xml.LoadXml(reader.ReadToEnd());
  29:  
  30:                 reader.Close();
  31:                 dataStream.Close();
  32:                 myResp.Close();
  33:             }
  34:         }
  35:         catch
  36:         {
  37:             xml = null;
  38:         }
  39:  
  40:         return xml;
  41:     }
  42:  
  43:     private static UserLocation ParseUserLocation(XmlDocument xml)
  44:     {
  45:         UserLocation location = null;
  46:         if (xml != null)
  47:         {
  48:             try
  49:             {
  50:                 XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable);
  51:                 nsMgr.AddNamespace("gml", "http://www.opengis.net/gml");
  52:                 
  53:                 XmlNode node = xml.SelectSingleNode("/HostipLookupResultSet/gml:featureMember/Hostip", nsMgr);
  54:                 if (node != null)
  55:                 {
  56:                     location = new UserLocation();
  57:                     XmlNode childNode = node.SelectSingleNode("gml:name", nsMgr);
  58:                     if (childNode != null)
  59:                         location.City = childNode.InnerText;
  60:  
  61:                     childNode = node.SelectSingleNode("countryName", nsMgr);
  62:                     if (childNode != null)
  63:                         location.Country = childNode.InnerText;
  64:  
  65:                     childNode = node.SelectSingleNode("countryAbbrev", nsMgr);
  66:                     if (childNode != null)
  67:                         location.CountryAbbrev = childNode.InnerText;
  68:  
  69:                     childNode = node.SelectSingleNode("ipLocation/gml:pointProperty/gml:Point/gml:coordinates", nsMgr);
  70:                     if (childNode != null)
  71:                     {
  72:                         string[] coord = childNode.InnerText.Split(',');
  73:                         if (coord.Length == 2)
  74:                         {
  75:                             double tmp = 0.0;
  76:                             double.TryParse(coord[0], out tmp);
  77:                             location.Longitude = tmp;
  78:                             double.TryParse(coord[1], out tmp);
  79:                             location.Latitude = tmp;
  80:                         }
  81:                     }
  82:  
  83:                     //make it null because it couldn't find it
  84:                     if (location.CountryAbbrev == "XX")
  85:                         location = null;
  86:                 }
  87:             }
  88:             catch
  89:             {
  90:                 location = null;
  91:             }
  92:         }
  93:         return location;
  94:     }
  95: }

As you can see. First we use the request API from .NET to make a request to the service and parse the request into an XML. Then we use the XML to parse it into our UserLocation object which will then be used by our web application. This is not a critical part of my application, so I decided that for any problem that I might encounter I will return null. In the web app I will only use the information if it’s not null.

   1: UserLocation location = GeoLocation.Locate(Request.UserHostAddress);
   2: if (location != null)
   3: {
   4:     //TODO: Do something with it
   5:     //location.City
   6:     //location.Country 
   7:     //location.CountryAbbrev 
   8:     //location.Latitude
   9:     //location.Longitude 
  10: }

The code above shows how to use the GeoLocation helper method from the web page or any other object.

Enjoy and Happy Programming!

Comments (4) -

Personally i use http://www.ipaddressgeolocation.com" title="http://www.ipaddressgeolocation.com">http://www.ipaddressgeolocation.com . They provide location via Google Maps, which is more informative.

Reply

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

Reply

It helped me with ocean of knowledge so I really believe you will do much better in the future I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer!

Reply

send code

Reply

Add comment

biuquote
Loading