C# .NET - how to detect the country and state by ip address in windows application

Asked By Reena Jain on 04-Feb-10 09:52 AM

In windows application how to detect the country and state by ip address. Please provide code for it.

F Cali replied to Reena Jain on 04-Feb-10 10:05 AM

Here's an article by Peter entitled "Build an IP to Country Geocoding Library with .NET" that may be able to help you:



Sakshi a replied to Reena Jain on 04-Feb-10 10:06 AM

code to detect the ip address:

public string IpAddress()
    string strIpAddress;
    strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (strIpAddress == null)
       strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
    return strIpAddress;

conver ip address to ip number:

public double IPAddressToNumber(string IPaddress)
    int i;
    string [] arrDec;
    double num = 0;
    if (IPaddress == "")
       return 0;
       arrDec = IPaddress.Split('.');
       for(i = arrDec.Length - 1; i >= 0 ; i --)
          num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
       return num;

to find the country :

Example: the IP Address converts to IP Number 3401190660. It is between the beginning and the ending of the following IP numbers:

From the IP-Country recordset, the Country_Name with this IP number range is Malaysia, the Country_Code is MY.

So once you have the IP Number, here's the SQL Query to locate the matching recordset:

SELECT country_name FROM ip_to_country WHERE
[your IP number] BETWEEN ip_start AND ip_end
Santhosh N replied to Reena Jain on 04-Feb-10 11:01 AM
To be clear you can actually find it in many ways from the services online but the fact is as there could be ips from different countries for different users across, its not 100% accurate and you can go through this healthy http://www.velocityreviews.com/forums/t73838-detect-country-c.html..

mv ark replied to Reena Jain on 04-Feb-10 11:06 PM
Try this web service to detect the country and state by ip address - http://ip-to-country.webhosting.info/node/view/21

Better still they offer a regularly updated free IP to Country database that you can load into your local database. You can get it from this link - http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip

Follow the instructions at this link - http://devfun.blogspot.com/2005/03/country-from-ip.html to use the database.

Also check this related article - http://www.eggheadcafe.com/articles/20051109.asp

Note that the  IP to Country database are constantly updated and may not always be precise. If you need accuracy you may have to go for a commercial database like this one - http://www.maxmind.com/app/ip-location