There are some free and some commercial database that can tell you from the ip, where is coming from.
The free database from maxmind [*]: http://dev.maxmind.com/geoip/geolite
and two commercial:
http://www.ip2location.com
http://www.maxmind.com
In this site you can also find asp.net examples on how you can use that data, but also they have other free services that you can use and see where the use is come from.
Get api samples together with the database from: http://www.maxmind.com/download/geoip/
If only the country is what you need for then this database file
http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
contains only the country, and is small compared with the rest.
How this works in few words: The database is in format of:
"1.20.0.0","1.20.255.255","18087936","18153471","TH","Thailand"
"1.21.0.0","1.21.255.255","18153472","18219007","JP","Japan"
"1.22.0.0","1.23.255.255","18219008","18350079","IN","India"
"1.24.0.0","1.31.255.255","18350080","18874367","CN","China"
the long numbers are the translation of the ip. So you read the IP of your user and then with a function you convert it to long and then you search the database, where is this long number fits.
public long addrToNum(IPAddress Address)
{
byte[] b = BitConverter.GetBytes(Address.Address);
if (b.Length == 8)
return (long)(((long)16777216 * b[0]) + ((long)(65536 * b[1])) + ((long)(256 * b[2])) + b[3]);
else
return 0;
}
So if you add them in database then you index the database on this long numbers and look where the ip is in as:
Select TOP 1 * from GeoIPCountryWhois WITH (NOLOCK) Where @myIpToLong BETWEEN begin_num AND end_num
Its good to cache the result on a session variable and not search again and again on every page request.
[*] A big thanks to maxmind that still release the free database together with the commercial.