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.
This completes the article you can download the sample source code using the link below.
IPtoCountry.zip (4.66 kb)