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: }