Search code examples
c#locationip

IP and Location information


I've searched about ip & location for my website. I want to know where my visitor have entered the website. According to his location i will make some recordings, show the website with a different theme and so on.

I'm using Asp.Net, I would not use any providers or tools. I want to do it my own. How can I do it ? What shall I search ?


Solution

  • You'll need to use a third party service or tool to gather GeoLocation. I suggest trying out the IPInfoDB, http://www.ipinfodb.com , which is a free GeoLocation service. Once you sign up for an API key you can consume the service in C# as follows:

     public static GeoLocation HostIpToPlaceName(string ip)
        {
            string url = "http://api.ipinfodb.com/v2/ip_query.php?key={enterAPIKeyHere}&ip={0}&timezone=false";
            url = String.Format(url, ip);
    
            var result = XDocument.Load(url);
    
            var location = (from x in result.Descendants("Response")
                            select new GeoLocation
                            {
                                City = (string)x.Element("City"),
                                Region = (string)x.Element("RegionName"),
                                CountryId = (string)x.Element("CountryName")
                            }).First();
    
            return location;
        }
    

    There are many services that provide GeoLocation but IPInfoDB is free and has worked well for me.

    You can also gather this information on the client side using HTML5 as demonstrated at http://html5demos.com/geo . Of course if you want to use this information in your code you would somehow have to pass it to the backend.