Track visitor location using IP Address

Track visitor location using IP Address


Track visitor location using IP AddressTracking your website visitor's geographical location ie. country, region, city, latitude, longitude, ZIP code, ISP and domain name is an integral part of your website visitor statistics and helps you to identify the locations from where you are getting the maximum traffic and tune your webpages accordingly.

You can easily tap this information in a two step process using IP2Location's proprietary IP address lookup database and without invading Internet user's privacy. But before you proceed further it is important that you first collect the visitors' IP address. Get the example code to retrieve visitor's IP address using ASP, PHP, JSP & ColdFusion here.

Step 1: Convert the visitor's IP address to an IP Number.

IP address (IPV4) is divided into 4 sub-blocks. Each sub-block has a different weight number each powered by 256. IP number is being used in the database because it is efficient to search between a range of numbers in database.

IP Number = 16777216*w + 65536*x + 256*y + z (1)
where IP Address = w.x.y.z

For example, if IP address is "202.186.13.4", then its IP Number "3401190660" is based on the formula (1).

IP Address = 202.186.13.4

So, w = 202, x = 186, y = 13 and z = 4

IP Number = 16777216*202 + 65536*186 + 256*13 + 4
= 3388997632 + 12189696 + 3328 + 4
= 3401190660

To reverse IP number to IP address,

w = int ( IP Number / 16777216 ) % 256
x = int ( IP Number / 65536 ) % 256
y = int ( IP Number / 256 ) % 256
z = int ( IP Number ) % 256

where % is the mod operator and int is return the integer part of the division.

Use these example ASP, PHP, ColdFusion, C#, VB.NET functions To Convert IP Address to IP Number.

Step 2: Search the IP-Country database to match a unique record that has the IP Number fitting between the Beginning IP Number and Ending IP Number.

For example, IP Address "202.186.13.4" is equivalent to IP Number "3401190660". It belongs to the following record in the database because it is between the beginning and the ending of IP number.

"3401056256","3401400319","MY","MALAYSIA"

From the recordset, the Country Name is Malaysia and Country Code is MY.

Example SQL Query to fetch the matching recordset.

SELECT [COUNTRY NAME COLUMN] FROM [IP-COUNTRY TABLE] WHERE 
[SEARCH IP NO] BETWEEN [IP FROM COLUMN] AND [IP TO COLUMN]
The IP-Country database is available for free while you will have to purchase the more detailed databases which include details like region, city, latitude, longitude, ZIP code, ISP and domain name for the IP address.

You can download the IP2Country database here. Then import this database into your MS-SQL, MS-ACCESS, PL/SQL, MySQL or other RDMS and use the query string above to get the matching recordset.