Click here to Skip to main content
15,867,965 members
Articles / Programming Languages / C#

Easy to Track the Geographical Location Based on IP Address

Rate me:
Please Sign up or sign in to vote.
4.80/5 (41 votes)
2 Mar 2010CPOL2 min read 162.3K   5.7K   114   40
Easy to track the geographical location based on IP Address

Table of Contents

Introduction

Developers are very much familiar with the use of IP tracking system, Microsoft Visual Studio .NET provides a number of class, methods to do this. This article is not about getting the user IP only, but also finds the geographical location of a user who is browsing your ASP.NET application. For example, you have an ASP.NET application, your hosting is done, your web address is suppose ”www.xyz.com”, now you want to track / maintain a log of the visitors IP with the location something like:

IP: XXX.XXX.XXX.XXX, TIMESTAMP: 3/2/2010 4:18:39 PM, COUNTRY= BANGLADESH, 
COUNTRY CODE= BD, CITY= DHAKA, etc.

Sample output figure:

Image 1

Quick Overview

Before we start, we need to know some basic knowledge, on System.Net, System.Data namespace provide by Microsoft Visual Studio .Net, HTTP Server variables.

More information can be found at this link.

How to Achieve

If you search for the solution on the internet; you may get many ways to do it. For example, you can use web service or download database containing the location mapped with the IP, but most of them are not free to use / allow you to a very limited number of hits per day… I found some sites that allow you free access for getting the user location from IP, some of the site(s) are listed below:

Note: All the above listed addresses reply in standard XML format.

How to Use the Services

In this section, I would like to discuss how to use the site(s) to retrieve a user geographical location. You can choose any one of them, before that you need to know what are the parameters required, let's start one by one:

(i)http://freegeoip.appspot.com

Parameter: IP Address (xxx.xxx.xxx.xxx).
URL sample: http://freegeoip.appspot.com/xml/xxx.xxx.xxx.xxx
Output: Standard XML

XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Status>true</Status>
    <Ip>xxx.xxx.xxx.xxx</Ip>
    <CountryCode>BD</CountryCode>
    <CountryName>Bangladesh</CountryName>
    <RegionCode>81</RegionCode>
    <RegionName>Dhaka</RegionName>
    <City>Dhaka</City>
    <ZipCode></ZipCode>
    <Latitude>23.723</Latitude>
    <Longitude>90.4086</Longitude>
</Response>
(ii)http://ws.cdyne.com/
  • Parameter: IP Address (xxx.xxx.xxx.xxx) & License Key
  • URL sample: http://ws.cdyne.com/ip2geo/ip2geo.asmx/ResolveIP?ipAddress=xxx.xxx.xxx.xxx&licenseKey=0
  • Output: Standard XML
XML
<?xml version="1.0" encoding="utf-8"?>
<IPInformation xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ws.cdyne.com/">
  <City>Dhaka</City>
  <StateProvince>81</StateProvince>
  <Country>Bangladesh</Country>
  <Organization />
  <Latitude>23.72301</Latitude>
  <Longitude>90.4086</Longitude>
  <AreaCode>0</AreaCode>
  <TimeZone />
  <HasDaylightSavings>false</HasDaylightSavings>
  <Certainty>90</Certainty>
  <RegionName />
  <CountryCode>BD</CountryCode>
</IPInformation>

Blocks of code should be set as style "Formatted" like this:

(iii)http://ipinfodb.com/
  • Parameter: IP Address (xxx.xxx.xxx.xxx)
  • URL sample:http://ipinfodb.com/ip_query.php?ip=xxx.xxx.xxx.xxx0
  • Output: Standard XML
XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Ip>xxx.xxx.xxx.xxx</Ip>
  <Status>OK</Status>
  <CountryCode>BD</CountryCode>
  <CountryName>Bangladesh</CountryName>
  <RegionCode>81</RegionCode>
  <RegionName>Dhaka</RegionName>
  <City>Dhaka</City>
  <ZipPostalCode></ZipPostalCode>
  <Latitude>23.7231</Latitude>
  <Longitude>90.4086</Longitude>
  <Timezone>6</Timezone>
  <Gmtoffset>6</Gmtoffset>
  <Dstoffset>6</Dstoffset>
</Response>

Get the User IP

I use a very common technique. Actually this is nothing but the using of HTTP server variables. The following server variables are used for this purpose.

  • HTTP_X_FORWARDED_FOR
  • REMOTE_ADDR

A sample code snippet is given below:

C#
private string GetVisitor()
    {        
        string strIPAddress = string.Empty;
        string strVisitorCountry = string.Empty;

        strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (strIPAddress == "" || strIPAddress == null)
            strIPAddress = Request.ServerVariables["REMOTE_ADDR"];

        Tools.GetLocation.IVisitorsGeographicalLocation _objLocation;
        _objLocation = new Tools.GetLocation.ClsVisitorsGeographicalLocation();

        DataTable _objDataTable = _objLocation.GetLocation(strIPAddress);

        if (_objDataTable != null)
        {
            if (_objDataTable.Rows.Count > 0)
            {
                strVisitorCountry = 
                            "IP: "
                            + strIPAddress
                            + ", TIMESTAMP: " 
                            + Convert.ToString(System.DateTime.Now)     
                            + ", CITY: "
                            + Convert.ToString(_objDataTable.Rows[0]["City"]).ToUpper()
                            + ", COUNTRY: "
                            + Convert.ToString(_objDataTable.Rows[0]
					["CountryName"]).ToUpper()
                            + ", COUNTRY CODE: "
                            + Convert.ToString(_objDataTable.Rows[0]
					["CountryCode"]).ToUpper();
            }
            else
            {
                strVisitorCountry = null;
            }
        }
        return strVisitorCountry;
    }

Get the User Location

To get the location, you just need to use the following provided by Microsoft Visual Studio .NET:

  • WebRequest
  • WebResponse
  • WebProxy

More information can be found at this link.

A sample code snippet is given below:

C#
public DataTable GetLocation(string strIPAddress)
        {
            //Create a WebRequest with the current Ip
            WebRequest _objWebRequest =
                WebRequest.Create(http://freegeoip.appspot.com/xml/ 
		//http://ipinfodb.com/ip_query.php?ip=
                               + strIPAddress);
            //Create a Web Proxy
            WebProxy _objWebProxy =
               new WebProxy("http://freegeoip.appspot.com/xml/"
                         + strIPAddress, true);

            //Assign the proxy to the WebRequest
            _objWebRequest.Proxy = _objWebProxy;

            //Set the timeout in Seconds for the WebRequest
            _objWebRequest.Timeout = 2000;

            try
            {
                //Get the WebResponse 
                WebResponse _objWebResponse = _objWebRequest.GetResponse();
                //Read the Response in a XMLTextReader
                XmlTextReader _objXmlTextReader
                    = new XmlTextReader(_objWebResponse.GetResponseStream());

                //Create a new DataSet
                DataSet _objDataSet = new DataSet();
                //Read the Response into the DataSet
                _objDataSet.ReadXml(_objXmlTextReader);

                return _objDataSet.Tables[0];
            }
            catch
            {
                return null;
            }
        } // End of GetLocation		 

Conclusion

I hope this might be helpful to you! Enjoy.

References

  • MSDN

History

  • 2nd March, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 1 Pin
vinayakJJ14-Aug-13 1:24
vinayakJJ14-Aug-13 1:24 
GeneralIts not working now, saying remote server not found,please update code. Pin
Punit Belani25-Jul-13 20:34
Punit Belani25-Jul-13 20:34 
GeneralMy vote of 5 Pin
csharpbd22-Nov-12 19:50
professionalcsharpbd22-Nov-12 19:50 
QuestionResult of this Project Pin
jsjsjsjsjsjsjsjsjsjs19-Aug-12 7:43
jsjsjsjsjsjsjsjsjsjs19-Aug-12 7:43 
AnswerRe: Result of this Project Pin
Md. Marufuzzaman10-Sep-12 19:46
professionalMd. Marufuzzaman10-Sep-12 19:46 
GeneralMy vote of 5 Pin
tanweer1-Jul-12 18:54
tanweer1-Jul-12 18:54 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman10-Sep-12 19:44
professionalMd. Marufuzzaman10-Sep-12 19:44 
GeneralMy vote of 5 Pin
Member 105108224-Apr-12 23:09
professionalMember 105108224-Apr-12 23:09 
GeneralTrust is really not an issue but this idea would be great if my compiled and published webpage returned the right location Pin
RedDk25-May-11 9:05
RedDk25-May-11 9:05 
GeneralRe: Trust is really not an issue but this idea would be great if my compiled and published webpage returned the right location Pin
Md. Marufuzzaman25-May-11 9:30
professionalMd. Marufuzzaman25-May-11 9:30 
GeneralMy vote of 5 Pin
Roger Wright24-Mar-11 8:51
professionalRoger Wright24-Mar-11 8:51 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman25-May-11 9:36
professionalMd. Marufuzzaman25-May-11 9:36 
Thanks......
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

Generalnice - have 5 Pin
Pranay Rana2-Jan-11 19:08
professionalPranay Rana2-Jan-11 19:08 
GeneralRe: nice - have 5 Pin
Md. Marufuzzaman5-Oct-11 22:53
professionalMd. Marufuzzaman5-Oct-11 22:53 
GeneralMy vote of 5 Pin
Tasnia.Maruf20-Sep-10 0:19
Tasnia.Maruf20-Sep-10 0:19 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman1-Oct-10 18:16
professionalMd. Marufuzzaman1-Oct-10 18:16 
GeneralMy vote of 1 Pin
PanagiotisG8-Mar-10 22:42
PanagiotisG8-Mar-10 22:42 
GeneralYour vote of 1 is improper and should be removed Pin
Dennis Dykstra10-Mar-10 5:27
Dennis Dykstra10-Mar-10 5:27 
GeneralRe: Your vote of 1 is improper and should be removed Pin
Md. Marufuzzaman10-Mar-10 6:02
professionalMd. Marufuzzaman10-Mar-10 6:02 
GeneralRe: My vote of 1 Pin
Roger Wright24-Mar-11 8:51
professionalRoger Wright24-Mar-11 8:51 
GeneralRe: My vote of 1 Pin
Mohibur Rashid5-Jan-12 14:14
professionalMohibur Rashid5-Jan-12 14:14 
GeneralRe: My vote of 1 Pin
Md. Marufuzzaman5-Jan-12 18:55
professionalMd. Marufuzzaman5-Jan-12 18:55 
GeneralMy vote of 1 Pin
JohnMcPherson12-Mar-10 9:34
JohnMcPherson12-Mar-10 9:34 
GeneralRe: My vote of 1 Pin
Md. Marufuzzaman2-Mar-10 18:28
professionalMd. Marufuzzaman2-Mar-10 18:28 
GeneralRe: My vote of 1 Pin
Mohibur Rashid5-Jan-12 14:15
professionalMohibur Rashid5-Jan-12 14:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.