Categories

Tags


Contact Form + Request.UserHostAddress = Country [State]

A recent project of mine had me creating a very basic contact form for a simple marketing website.  It just so happens that shortly after creating the contact form I had to use a contact form on Ryan Lanciaux's blog and was impressed with the fact that when I received a response from Ryan, his email contained the country that my IP originated from (I know... such a simple thing impressed me).  I now had to figure out how to add some of this sweetness to my own simple contact form.  I found a couple of different methods for getting country [state] information from an IP and finally settled on a method that utilized the hostip.info website/database.  The hostip website allows you to get the data in a couple different ways, you can get raw text (which my sample demonstrates); you can also get an XML data dump that includes lat/long.  Here is a very basic method that can be used to get country and state information for an IP address:

    private string GetCountryStateForIP(string ip)
    {
        try
        {
            //http://api.hostip.info/?ip=12.215.42.19
            string ipUrl = "http://www.hostip.info/api/get.html?ip=" 
                + ip; 
            WebClient webClient = new WebClient(); 
            Byte[] ipInfoBytes = webClient.DownloadData(ipUrl); 
            UTF8Encoding encoding = new UTF8Encoding(); 
            string ipInfo = encoding.GetString(ipInfoBytes);

            return string.Format("IP: {0} {1}Data: {2}", 
                    ip, Environment.NewLine, ipInfo);
        }
        catch (Exception ex)
        {
            return string.Format("IP: {0} {1}Error: {2}", 
                    ip, Environment.NewLine, ex.Message);
        }
    }
 

The comment in the code above contains the URL that will return the XML feed.  My goal is to create a more robust method that gathers latitude and longitude information.  I would actually like to go as far as to then take that latitude and longitude and generate a link to that location using Google Maps

kick it on DotNetKicks.com

August 23, 2008 13:39 by jpsanders
E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed