How to determine if an IP address belongs to a country

前端 未结 11 1160
情歌与酒
情歌与酒 2020-12-07 17:55

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.

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 18:35

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

提交回复
热议问题