How to determine if an IP address belongs to a country

前端 未结 11 1171
情歌与酒
情歌与酒 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:27

    Here's how to do this with https://ipdata.co

    //Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
    //System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    
    //Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
    using System;
    using System.Net.Http;
    
    var baseAddress = new Uri("https://api.ipdata.co/78.8.53.5");
    
    using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
    {
    
      httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
    
      using(var response = await httpClient.GetAsync("undefined"))
      {
    
            string responseData = await response.Content.ReadAsStringAsync();
      }
    }
    

    Via Curl

    curl https://api.ipdata.co/78.8.53.5
    {
        "ip": "78.8.53.5",
        "city": "G\u0142og\u00f3w",
        "region": "Lower Silesia",
        "region_code": "DS",
        "country_name": "Poland",
        "country_code": "PL",
        "continent_name": "Europe",
        "continent_code": "EU",
        "latitude": 51.6461,
        "longitude": 16.1678,
        "asn": "AS12741",
        "organisation": "Netia SA",
        "postal": "67-200",
        "currency": "PLN",
        "currency_symbol": "z\u0142",
        "calling_code": "48",
        "flag": "https://ipdata.co/flags/pl.png",
        "emoji_flag": "\ud83c\uddf5\ud83c\uddf1",
        "time_zone": "Europe/Warsaw",
        "is_eu": true,
        "suspicious_factors": {
            "is_tor": false
        }
    }⏎ 
    

提交回复
热议问题