How to determine if an IP address belongs to a country

27,421

Solution 1

You can use this SQL data in your project to determine that: IP address geolocation SQL database. Download that data and import it into your database to run checks locally.

Or you can use their free API that returns XML containing the country code and country name. You'd make a request to the following URL with the IP address you wanted to check, as seen in this example:

http://ipinfodb.com/ip_query_country.php?ip=74.125.45.100

Returns:

<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
</Response>

Solution 2

Just a simple API call e.g. https://ipapi.co/8.8.8.8/country/

US

Here's a C# example with working fiddle :

using System;
using System.Net;
using System.IO;
using System.Text;


public class Program
{
    public static void Main()
    {

      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

      HttpWebRequest request   = (HttpWebRequest)WebRequest.Create("https://ipapi.co/8.8.8.8/country/");
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();

      var reader = new System.IO.StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII);
      Console.WriteLine(reader.ReadToEnd());

    }
}

Solution 3

Here is a free IP Address to Country database.

Solution 4

you can ask google to do it for you.

there are also services that you can pay for you want:

Solution 5

If you don't want to use an API like perhaps hostip.info, then I'd suggest subscribing to maxmind and running a host lookup database locally.

Share:
27,421

Related videos on Youtube

RC1140
Author by

RC1140

Updated on December 07, 2021

Comments

  • RC1140
    RC1140 over 2 years

    How would i determine the country that a spcific IP address is originating from using c#. I need to use this to check if connections originate from a specific country.

    • RC1140
      RC1140 over 14 years
      I need the data to be available offline since it will be used for stats. Because of this will i will be using the sql option
  • Marbal
    Marbal about 14 years
    Please note that the IP assignments change occasionally. So remember to update your database occasionally. (The frequency of updates you need depends on what you're doing; for simple stats you may decide that annual updates are OK).
  • Shaul Behr
    Shaul Behr about 13 years
    This has now changed: you have to register now (free) to be able to use their API. See here: ipinfodb.com/ip_location_api.php
  • Pluto
    Pluto over 3 years
    It looks like this has changed since, the site now has a link in the main navigation eventually leads to the following for downloading: download.ip2location.com/lite Attribution required but free for commercial use. Additional info here (ie. IP's must be converted to INT's): lite.ip2location.com/database-ip-country