ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Find Visitors Geographic Location using IP Address in ASP.Net
Author Name: Mudassar Khan Published Date: April 12, 2009
Filed Under :
ASP.Net
Views: 13402

In my previous article I explained, How to get IP Address of Visitor's Machine in ASP.Net

In this article, I am explaining to find location of the user based on its IP Address. There are many methods to do the same.

1.     Get a free database which has IP to Location mapping

2.     Call a web service that does the same for you.

Many times it is asked on asp.net forums an easy way to get the location of the user based on its IP address. And too the web service should be free since many web services either are not free and the ones which are free set some limitations on the number of request per day. And if some are free they are not easy to use.

Then I found the following web service which provide this service absolutely free and that too without any complex interface to do the same

http://freegeoip.appspot.com/

The above website provides free IP Geolocation Web Service that returns data in three formats .

1.     XML   [Extended Markup Language]

2.     CSV   [Comma Separated Values]

3.     JSON [JavaScript Object Notation]

Here I am explaining how to get the data in XML format.

Calling the web service is also easy you just need to pass the IP Address in URL and it will display the data

http://freegeoip.appspot.com/xml/122.169.8.137

There are other free services too that return data in same format e.g.

http://ipinfodb.com/ip_query.php?ip=122.169.8.137

Both the above returns you the output in XML Format for the IP Address in the URL

The returned XML looks as below

  <?xml version="1.0" encoding="UTF-8" ?>

  <Response>

    <Status>true</Status>

    <Ip>122.169.8.137</Ip>

    <CountryCode>IN</CountryCode>

    <CountryName>India</CountryName>

    <RegionCode>16</RegionCode>

    <RegionName>Maharashtra</RegionName>

    <City>Bombay</City>

    <ZipCode />

    <Latitude>18.975</Latitude>

    <Longitude>72.8258</Longitude>

  </Response>

 

As you can see with the IP Address you can find

1.     Country

2.     City

3.     Region

4.     Latitude

5.     Longitude

Now I’ll explain how to consume this xml and display data on web page in asp.net.

Below function GetLocation creates a WebRequest and WebProxy and make a call to the url

Then the xml response is received as WebResponse and then Xml in WebResponse is read by the XMLTextReader and finally filled into a DataSet.

C#

 

private DataTable GetLocation(string ipaddress)

{

    //Create a WebRequest

    WebRequest rssReq =

        WebRequest.Create("http://freegeoip.appspot.com/xml/"

            + ipaddress);

 

    //Create a Proxy

    WebProxy px =

       new WebProxy("http://freegeoip.appspot.com/xml/"

            + ipaddress, true);

 

    //Assign the proxy to the WebRequest

    rssReq.Proxy = px;

 

    //Set the timeout in Seconds for the WebRequest

    rssReq.Timeout = 2000;

    try

    {

        //Get the WebResponse

        WebResponse rep = rssReq.GetResponse();

 

        //Read the Response in a XMLTextReader

        XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());

 

        //Create a new DataSet

        DataSet ds = new DataSet();

 

        //Read the Response into the DataSet

        ds.ReadXml(xtr);

        return ds.Tables[0];

    }

    catch

    {

        return null;

    }

}

 

     

VB.Net

Private Function GetLocation(ByVal ipaddress As String) _

    As DataTable

        'Create a WebRequest

        Dim rssReq As WebRequest = _

        WebRequest.Create("http://freegeoip.appspot.com/xml/" _

        & ipaddress)

 

        'Create a Proxy

        Dim px As New WebProxy("http://freegeoip.appspot.com/xml/" _

        & ipaddress, True)

 

        'Assign the proxy to the WebRequest

        rssReq.Proxy = px

 

        'Set the timeout in Seconds for the WebRequest

        rssReq.Timeout = 2000

        Try

            'Get the WebResponse

            Dim rep As WebResponse = rssReq.GetResponse()

 

            'Read the Response in a XMLTextReader

            Dim xtr As New XmlTextReader(rep.GetResponseStream())

 

            'Create a new DataSet

            Dim ds As New DataSet()

 

            'Read the Response into the DataSet

            ds.ReadXml(xtr)

            Return ds.Tables(0)

        Catch

            Return Nothing

        End Try

    End Function

 

Now I’ll call this function in page load event in order to display the results using labels on the page.

First I am retrieving the visitor's IP Address and then based on the IP Address I am finding the Location using the GetLocation function which returns a datatable. Then finally I check if the DataTable has rows, if it has it the data is displayed in Label

          

C#

//Get IP Address

string ipaddress;

ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (ipaddress == "" || ipaddress == null)

    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

 

DataTable dt = GetLocation(ipaddress);

if (dt != null)

{

    if (dt.Rows.Count > 0)

    {

        lblCity.Text = dt.Rows[0]["City"].ToString();

        lblRegion.Text = dt.Rows[0]["RegionName"].ToString();

        lblCountry.Text = dt.Rows[0]["CountryName"].ToString();

        lblCountryCode.Text = dt.Rows[0]["CountryCode"].ToString();

    }

    else

    {

 

    }

}

 

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        'Get Ip address

        Dim ipaddress As String

        ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")

        If ipaddress = "" Or ipaddress Is Nothing Then

            ipaddress = Request.ServerVariables("REMOTE_ADDR")

        End If

        Dim dt As DataTable = GetLocation(ipaddress)

        If dt IsNot Nothing Then

            If dt.Rows.Count > 0 Then

                lblCity.Text = dt.Rows(0)("City").ToString()

                lblRegion.Text = dt.Rows(0)("RegionName").ToString()

                lblCountry.Text = dt.Rows(0)("CountryName").ToString()

                lblCountryCode.Text = dt.Rows(0)("CountryCode").ToString()

            Else

            End If

        End If

End Sub



The figure below describes how the location will be displayed.


Location based on IP Address



This completes the article you can download the sample source code using the link below.

IPtoCountry.zip (4.66 kb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Dennis said:
This is very nice clean and simple. How come it does not return a zipcode It returns everything as expected but of course I need the zipcode. Any ideas on how to make this return the zipbr br Thanks
January 07, 2010  

Mudassar Khan said:
Reply To: Dennis
It depends on the service providers you can try out some paid services that might provide zip codes
January 07, 2010  

Nisha Alosious said:
hello sirbr br While executting i am getting an error like this please help me out this.br br The remote server returned an error: (503) Serverbr br Nisha
January 08, 2010  

Matt said:
thanks so much Mudassar Khan.
January 24, 2010  

Mudassar Khan said:
Reply To: Nisha Alosious
Hi Nisha,

That may be because the service might be down due to some reason
January 24, 2010  

Amrith said:
Hi there ...br Great tutorial but fr some reason it doesnt seem to be working. The IP address is retrieved but no other details are gettin displayed. What could be the possible reasonbr Thanks.
February 05, 2010  

Mudassar Khan said:
Reply To: Amrith
Hi,

It depends on the third party service. You need to verify with them. There might be some issue with their servers
February 05, 2010  

vijay said:
nice one and simple
February 20, 2010  

max said:
Excellent Thanks For Posting
March 04, 2010  

ezraeil said:
hibr You are accessing this page from a forbidden country.br I encountered this problem Shvdm on this site. For my country is prohibited. Sites like this site are not the samebr help mebr Thank you
March 08, 2010  

Mudassar Khan said:
Reply To: ezraeil
Sorry but the location information totally depends on the service you are using for that you cannot do anything in code
March 08, 2010  

Rahul said:
Hibr Thanks for the tutorial but it is not working properlybr I am getting errorbr br The remote server returned an error: (503) Server Unavailable.br br Could you please help me out
April 18, 2010  

Mudassar Khan said:
Reply To: Rahul
If you go through the article I have given 2nd service also http://ipinfodb.com/ip_query.php?ip=122.169.8.137

Please use that.

Thanks
April 18, 2010  

svk said:
Along with the br lblCity.Text dt.Rows(0)(City).ToString()br br lblRegion.Text dt.Rows(0)(RegionName).ToString()br br lblCountry.Text dt.Rows(0)(CountryName).ToString()br br lblCountryCode.Text dt.Rows(0)(CountryCode).ToString()br br what other details can we get
May 14, 2010  

Mudassar Khan said:
Reply To: svk
You will get everything shown in the XML above just add the proper column names i.e. Latitude and Longitude to get their values
May 15, 2010  

SVK said:
a query related to samebr cant the same code work for intranet application if the system have net conectivitybr or is there any way to get the location of the users from intranet application
May 17, 2010  

pavani said:
Thanks for code .I tried your code am getting wrong details br am in India and i get br City:Romebr Region:Laziobr Country:Italybr CountryCode:ITbr why is to so
May 18, 2010  

Mudassar Khan said:
Reply To: pavani
On local machine you will get random values hence simply ignore


May 19, 2010  

Mudassar Khan said:
Reply To: SVK
On local machine it displays randome location as your IP is 127.0.0.1
May 19, 2010  

Mugs said:
hey i have used the code above with both the web services that u have mentioned still it isnt displaying the information requiredbr pls help
June 13, 2010  

Mudassar Khan said:
Reply To: Mugs
The above article is using those services and you can see it is displaying the data
June 18, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code