How to determine if an IP address belongs to a country

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>

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());

    }
}