robbanp
I'm the co-founder of this website and the tech lead. Follow me on: twitter.com/robertpohl
Blog

The Rob blog

I'm Robert Pohl, the creator and co-founder to ThatsToday. I blog mostly about technology and internet related topics. Follow me on Twitter @robertpohl
Subscribe to RSS

When building web apps it is often that you customize content depending on the geographical location of the visitors. The easiest way to achieve this information is that you ask them where they are from, by choosing a country from a long drop-list. The thing is that we developers always want to solve things automatically by code (even when it is not really necessary). I found a excellent free IP to GeoLocation service http://ipinfodb.com, and hacked together a small class that queries the API with the IP address from the visitor.

The code:

 

using System.Net;
using System.Xml;

namespace Portal.Web.API.Geo
{
    public class IPGeoLocation
    {
        private const string Service = "http://ipinfodb.com/ip_query.php?ip=";
        public string City = string.Empty;
        public string Country = string.Empty;
        public bool FoundGeoData;
        public string Ip = string.Empty;

        public IPGeoLocation(string ip)
        {
            var request = (HttpWebRequest) WebRequest.Create(Service + ip);
            request.SendChunked = true;
            request.Timeout = 5000;

            var response = (HttpWebResponse) request.GetResponse();
            var xd = new XmlDocument();
            xd.Load(response.GetResponseStream());
            if (xd.GetElementsByTagName("Status")[0].InnerText.ToLower() == "ok")
            {
                Country = GetTextValue(xd, "CountryName");
                City = GetTextValue(xd, "City");
                FoundGeoData = true;
            }
            else
            {
                FoundGeoData = false;
            }
        }

        private string GetTextValue(XmlDocument xd, string name)
        {
            return xd.GetElementsByTagName(name).Count > 0 ? xd.GetElementsByTagName(name)[0].InnerText : string.Empty;
        }
    }
}

 

How to use it:

 

IPGeoLocation ipGeo = new IPGeoLocation(Request.UserHostAddress);
            if(ipGeo.FoundGeoData)
            {
                Response.Write("Country: "+ipGeo.Country+", City: "+ipGeo.City);
            }

 

This example only take care of the city and country, but you can easily extend it to get the long/lat. coordinates to use with Google Maps or similar. Enjoy!

Comments on this article

Add your comment
Sign In

Not a member yet?

Signing up is FREE and will only take 15 seconds!

Facebook Login

Sign In

E-mail address:
Password:
Remember me
Sponsored links

Close