Friday, May 10, 2013

Locating IP Original Origin C#

I recently was trying to write a function that would allow me to trace an IP back to it's origin or at least return the city and state.  I didn't want to use Google API or any other type of fancy API.  After a few hours of R.N.D., I found a link to a generic site that's soul purpose is to grab your current location and return XML.  As I started to write my function to parse the XML.  I realized my typical way of parsing XML was having issues because of the way this sites XML tree was assembled.  After giving it some thought, I came to the conclusion that I needed to add a namespace manager to my XML document which is called XmlNamespaceManager.  In the example below you'll see my simple approach and how I was able to resolve this issue.  Hope this helps anyone having similar issues especially when it comes to consuming XML.  Happy Coding!!!
 private const string _hostIPUrl = "http://api.hostip.info/";

 public string GetLocation() 
  {
   WebClient client = new WebClient();
   Uri uri = new Uri(String.Format("{0}", _hostIPUrl));
   List location = new List();

   string xmlString = client.DownloadString(uri).ToString();

   XmlDocument doc = new XmlDocument();

   doc.LoadXml(xmlString);

   XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
   manager.AddNamespace("gml", "http://www.opengis.net/gml");

   XmlNode cityLocation = doc.SelectSingleNode("//HostipLookupResultSet/" +
   "gml:featureMember/Hostip/gml:name/text()", manager);

   return cityLocation.Value;
  }

No comments:

Post a Comment