2009-08-13 3 views
17

Wie würde ich feststellen, dass eine bestimmte IP-Adresse aus C# stammt? Ich muss dies verwenden, um zu überprüfen, ob Verbindungen aus einem bestimmten Land stammen.So ermitteln Sie, ob eine IP-Adresse zu einem Land gehört

+1

ich die Daten müssen offline verfügbar sein, da es für Statistiken verwendet werden. Aus diesem Grund werde ich die SQL-Option verwenden – RC1140

+0

Sie könnten auch Bulk-Lookups mit https://ipdata.co – Jonathan

Antwort

25

Sie können diese SQL-Daten in Ihrem Projekt verwenden, um Folgendes festzustellen: IP address geolocation SQL database. Laden Sie diese Daten herunter und importieren Sie sie in Ihre Datenbank, um Prüfungen lokal auszuführen.

Oder Sie können ihre kostenlose API verwenden, die XML mit dem Ländercode und dem Ländernamen zurückgibt. Sie würden eine Anfrage an die folgende URL machen mit der IP-Adresse, die Sie überprüfen wollen, wie in diesem Beispiel zu sehen:

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> 
+0

Bitte beachten Sie, dass die IP-Zuweisungen gelegentlich ändern. Denken Sie also daran, Ihre Datenbank gelegentlich zu aktualisieren. (Die Häufigkeit der Updates, die Sie benötigen, hängt davon ab, was Sie tun; für einfache Statistiken können Sie entscheiden, dass die jährlichen Updates in Ordnung sind). – user9876

+1

Dies hat sich jetzt geändert: Sie müssen sich jetzt registrieren (kostenlos), um ihre API verwenden zu können. Siehe hier: http://ipinfodb.com/ip_location_api.php –

1

Wenn Sie nicht wollen, Verwenden Sie eine API wie vielleicht hostip.info, dann würde ich vorschlagen, maxmind zu abonnieren und lokal eine Host-Lookup-Datenbank zu betreiben.

1

ip2cc - Nach Land und Russland nach IP-Adresse suchen Python-Modul mit Skript zum Erstellen einer Datenbank aus aktuellen offiziellen Daten.

Diese Python Nutzlasten (so oft wie Sie möchten) up-to-date Informationen von Regional Internet Registry Websites (arin, ripencc, apnic, lacnic, afrinic), wie shown in the source:

url_template = 'ftp://ftp.ripe.net/pub/stats/%s/delegated-%s-latest' 
sources = {} 
for name in ('arin', 'ripencc', 'apnic', 'lacnic', 'afrinic'): 
    sources[name] = url_template % (name, name) 

Sobald die Daten geladen, Abfragen können offline und sehr schnell beantwortet werden. Kann leicht geändert werden, um die ursprüngliche Frage direkt zu beantworten, oder verwendet von der Befehlszeile, um das Land zurückzugeben, das ein IP address gehört.

1

Ein weiterer Service, den Sie meinen eigenen verwenden könnte, ist, http://ipinfo.io, die zurück Lage, Organisation und andere Informationen:

$ curl ipinfo.io/8.8.8.8 
{ 
    "ip": "8.8.8.8", 
    "hostname": "google-public-dns-a.google.com", 
    "loc": "37.385999999999996,-122.0838", 
    "org": "AS15169 Google Inc.", 
    "city": "Mountain View", 
    "region": "California", 
    "country": "US", 
    "phone": 650 
} 

Siehe http://ipinfo.io/developers für weitere Informationen.

+0

um Json von Hand zu bekommen: "http://ipinfo.io/8.8.8.8/json" –

3

Nur eine einfache API Anruf z.B.https://ipapi.co/8.8.8.8/country/

US

Hier ist ein C# Beispiel mit 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()); 

    } 
} 
0

Hier ist, wie dies zu tun mit 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 Locken

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 
    } 
}⏎ 
0

Für die Offline-Datenbank können Sie die freie IP2Location LITE DB1

bekommen Um die Tabelle

CREATE DATABASE ip2location 
GO 

USE ip2location 
GO 

CREATE TABLE [ip2location].[dbo].[ip2location_db1](
    [ip_from] float NOT NULL, 
    [ip_to] float NOT NULL, 
    [country_code] nvarchar(2) NOT NULL, 
    [country_name] nvarchar(64) NOT NULL, 
) ON [PRIMARY] 
GO 

CREATE INDEX [ip_from] ON [ip2location].[dbo].[ip2location_db1]([ip_from]) ON [PRIMARY] 
GO 

CREATE INDEX [ip_to] ON [ip2location].[dbo].[ip2location_db1]([ip_to]) ON [PRIMARY] 
GO 

So importieren Sie die Daten

BULK INSERT [ip2location].[dbo].[ip2location_db1] 
    FROM 'C:\[path to your CSV file]\IP2LOCATION-LITE-DB1.CSV' 
    WITH 
    (
     FORMATFILE = 'C:\[path to your DB1.FMT file]\DB1.FMT' 
    ) 
GO 

Für die FMT-Datei

10.0 
5 
1 SQLCHAR 0 1 "\"" 0 first_double_quote Latin1_General_CI_AI 
2 SQLCHAR 0 20 "\",\"" 1 ip_from "" 
3 SQLCHAR 0 20 "\",\"" 2 ip_to "" 
4 SQLCHAR 0 2 "\",\"" 3 country_code Latin1_General_CI_AI 
5 SQLCHAR 0 64 "\"\r\n" 4 country_name Latin1_General_CI_AI 
zu erstellen

Die erste Zeile des FMT-Codes zeigt die Version von bcp an. Bitte ändern Sie die Version gemäß Ihrem installierten MS-SQL.

SQL Server 2016 12,0

SQL Server 2014 12.0

SQL Server 2012 11.0

SQL Server 2008/2008 R2 10.0

SQL Server 2005 9.0

SQL Server 2000 8.0

SQL Server 7.0 7.0

SQL Server 6.5 6.5

C# -Code zur Abfrage MSSQL

using System.Data.SqlClient; 
using System.Numerics; 
using System.Net; 
using System.Text; 
public class Form1 { 

    private void Form1_Load(object sender, System.EventArgs e) { 
     string ip = "8.8.8.8"; 
     this.IP2Location(ip); 
    } 

    private void IP2Location(string myip) { 
     IPAddress address = null; 
     if (IPAddress.TryParse(myip, address)) { 
      byte[] addrBytes = address.GetAddressBytes(); 
      this.LittleEndian(addrBytes); 
      UInt32 ipno = 0; 
      ipno = BitConverter.ToUInt32(addrBytes, 0); 
      string sql = "SELECT TOP 1 * FROM ip2location_db1 WHERE ip_to >= \'" + ipno.ToString() + "\'"; 
      object conn = new SqlConnection("Server=yourserver;Database=yourdatabase;User Id=youruserid;Password=yourpassword;"); 
      object comm = new SqlCommand(sql, conn); 
      SqlDataReader reader; 
      comm.Connection.Open(); 
      reader = comm.ExecuteReader(CommandBehavior.CloseConnection); 
      int x = 0; 
      object sb = new StringBuilder(250); 
      if (reader.HasRows) { 
       if (reader.Read()) { 
        for (x = 0; (x <= (reader.FieldCount() - 1)); x++) { 
         sb.Append((reader.GetName(x) + (": " + (reader.GetValue(x) + "\r\n")))); 
        } 
       } 
      } 

      reader.Close(); 
      MsgBox(sb.ToString()); 
     } 

    } 

    private void LittleEndian(ref byte[] byteArr) { 
     if (BitConverter.IsLittleEndian) { 
      List<byte> byteList = new List<byte>(byteArr); 
      byteList.Reverse(); 
      byteArr = byteList.ToArray(); 
     } 

    } 
} 
Verwandte Themen