Saturday, July 25, 2009

How to identify user's country by ip

In a 4 steps u can identify the user's country
u will discover that it is a very easy assignment

step 1:
Download the txt file from here, that represent the ip ranges of each country. when u save this file change his extension to csv.

step 2:
Import the csv file into your db and create table with the name [ip-to-country].

step 3:
By taking the user's IP with Request.UserHostAddress convert this string to uint by this function:

public uint IPAddressToLongBackwards(string IPAddr)
System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
byte[] byteIP = oIP.GetAddressBytes();

uint ip = (uint)byteIP[0] << 24;
ip += (uint)byteIP[1] << 16;
ip += (uint)byteIP[2] << 8;
ip += (uint)byteIP[3];

return ip;

step 4:
with this ip address (as uint) go to our [ip-to-country] table and select the country by this sql query(@ip is the uint ip address):

SELECT countryCode2
from [ip-to-country]
where ipFrom <= @ip
and ipTo >= @ip