October 14, 2006

How to get country information from IP address ?

Using some very simple maths and a IP-based geo-location reference table, you can find the exact physical location of you website visitors. This technique can be extended to retrieve visitor's IP address using ASP, PHP, JSP, Perl or ColdFusion.


The first step is to convert the visitor's IP address to an IP Number. Then we can search the IP-Country-Region-City database using IP number to match a record that has the IP Number between Beginning IP Number and Ending IP Number. Then, we can search the free IP-to-Country Database to match a unique record that has the IP number fits between From IP Number and To IP Number.

An IP Address is generally of the form w.x.y.z

The IP Number = 16777216*w + 65536*x + 256*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 (w = 202, x = 186, y = 13 and z = 4)

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

It falls in the following range of IP number in the table because it is between the "From IP number" and the "To IP number".

"begin_num","end_num","country","name"

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

From the IP range, the Country Name is Malaysia and Country Code is MY.
The country-level mapping database are available for free but you will have to pay for national, regional and metropolitan databases which reveal visitor details like region, city, latitude, longitude, ZIP code, ISP and domain name from IP address.