GeoLocate a visitor’s IP address and cache the results. (C#)

First, go over to http://ipinfodb.com , see how it works and get yourself an API key by signing up for free. If you’re looking to convert an visitors IP address into a geographic location, then here’s a quick code nugget in C#. Have fun!


  
  string ip = Request.ServerVariables["X-Forwarded-For"]
      
   public class LocationInfo
    {
        public string Country { get; set; }
        public string RegionName { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
        public float Latitude { get; set; }
        public float Longitude { get; set; }
    }

     public static LocationInfo HostIpToPlaceName(string ip)
        {
            ObjectCache cache = MemoryCache.Default;

            var key = "zzzzzgetyourowncodezzzzzz";
            string url = "http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=xml";
            
            url = String.Format(url,key, ip);
            var location = new LocationInfo();
            var result = cache[ip] as XDocument;
            try
            {
                if (result == null)
                {
                    result = XDocument.Load(url);
                    cache.Add(ip, result,
                   new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromDays(1) });
                }

          location = (from x in result.Descendants("Response")
                      select new LocationInfo
                    {
                     City = (string)x.Element("cityName"),
                     RegionName = (string)x.Element("regionName"),
                     Country = (string)x.Element("countryName"),
                     ZipCode = (string)x.Element("zipCode"),
                     Latitude = (float)x.Element("latitude"),
                     Longitude = (float)x.Element("longitude")
                    }).First();
            return location;
        }
    }

One thing to notice is that this caches the result for each unique IP address, so that you don’t have to call this API everytime you need this users location. Cheers!

Fork me on GitHub