2009-08-13 57 views
17

Làm cách nào để xác định quốc gia có địa chỉ IP spcific bắt nguồn từ việc sử dụng C#. Tôi cần sử dụng điều này để kiểm tra xem các kết nối có bắt nguồn từ một quốc gia cụ thể không.Cách xác định xem địa chỉ IP có thuộc về một quốc gia hay không

+1

tôi cần những dữ liệu khả dụng ẩn vì nó sẽ được sử dụng cho số liệu thống kê. Bởi vì điều này tôi sẽ sử dụng tùy chọn sql – RC1140

+0

Bạn cũng có thể thực hiện tra cứu số lượng lớn với https://ipdata.co – Jonathan

Trả lời

25

Bạn có thể sử dụng dữ liệu SQL này trong dự án của mình để xác định rằng: IP address geolocation SQL database. Tải xuống dữ liệu đó và nhập nó vào cơ sở dữ liệu của bạn để chạy kiểm tra cục bộ.

Hoặc bạn có thể sử dụng API miễn phí của họ trả về XML chứa mã quốc gia và tên quốc gia. Bạn muốn tạo ra một yêu cầu đến URL sau với địa chỉ IP mà bạn muốn kiểm tra, như đã thấy trong ví dụ này:

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

Xin lưu ý rằng các nhiệm vụ IP thỉnh thoảng thay đổi. Vì vậy, hãy nhớ cập nhật cơ sở dữ liệu của bạn đôi khi. (Tần suất cập nhật bạn cần phụ thuộc vào những gì bạn đang làm, đối với số liệu thống kê đơn giản, bạn có thể quyết định rằng cập nhật hàng năm là OK). – user9876

+1

Điều này đã thay đổi: bạn phải đăng ký ngay bây giờ (miễn phí) để có thể sử dụng API của họ. Xem tại đây: http://ipinfodb.com/ip_location_api.php –

1

Nếu bạn không muốn sử dụng một API giống như hostip.info, sau đó tôi khuyên bạn nên đăng ký maxmind và chạy một cơ sở dữ liệu tra cứu máy chủ lưu trữ cục bộ.

1

ip2cc - Tìm quốc gia và khu vực Nga theo địa chỉ IP Mô-đun Python có tập lệnh để tạo cơ sở dữ liệu từ dữ liệu chính thức cập nhật.

này Python tải tiện ích (thường xuyên như bạn muốn) up-to-date thông tin từ Regional Internet Registry trang web (arin, ripencc, apnic, lacnic, afrinic), như 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) 

Khi dữ liệu được được tải, các truy vấn có thể được trả lời ngoại tuyến và rất nhanh chóng. Có thể dễ dàng sửa đổi để trả lời trực tiếp câu hỏi gốc hoặc sử dụng từ dòng lệnh để trả lại quốc gia là IP address.

1

Một dịch vụ mà bạn có thể sử dụng là của riêng tôi, http://ipinfo.io, mà trả về vị trí, tổ chức và các thông tin khác:

$ 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 
} 

Xem http://ipinfo.io/developers để biết thêm thông tin.

+0

để lấy json bằng tay: "http://ipinfo.io/8.8.8.8/json" –

3

Chỉ cần gọi API đơn giản, ví dụ:https://ipapi.co/8.8.8.8/country/

Mỹ

Dưới đây là một ví dụ C# với 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

Dưới đây là làm thế nào để làm điều này với 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 
    } 
}⏎ 
0

Đối với cơ sở dữ liệu trực tuyến, bạn có thể nhận được miễn phí IP2Location LITE DB1

Để tạo bảng

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 

Để nhập dữ liệu

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 

Đối với các tập tin FMT

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 

Dòng đầu tiên của mã FMT cho biết phiên bản bcp. Vui lòng thay đổi phiên bản theo cài đặt MS-SQL của bạn.

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 đang 6,5 6,5

C# để truy vấn 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(); 
     } 

    } 
} 
Các vấn đề liên quan