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.
我如何确定特定IP地址源自使用c#的国家/地区。我需要使用它来检查连接是否来自特定国家/地区。
9 个解决方案
#1
25
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.
您可以在项目中使用此SQL数据来确定:IP地址地理定位SQL数据库。下载该数据并将其导入数据库以在本地运行检查。
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:
或者您可以使用他们的免费API返回包含国家/地区代码和国家/地区名称的XML。您将使用您要检查的IP地址向以下URL发出请求,如下例所示:
http://ipinfodb.com/ip_query_country.php?ip=74.125.45.100
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>
#2
3
Just a simple API call e.g. https://ipapi.co/8.8.8.8/country/
只是简单的API调用,例如https://ipapi.co/8.8.8.8/country/
US
我们
Here's a C# example with working fiddle :
这是一个带工作小提琴的C#示例:
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());
}
}
#3
2
you can ask google to do it for you.
你可以请谷歌为你做这件事。
- http://googlecode.blogspot.com/2008/08/two-new-ways-to-location-enable-your.html
- http://googlecode.blogspot.com/2008/08/two-new-ways-to-location-enable-your.html
there are also services that you can pay for you want:
您还可以支付以下服务:
- http://www.ip2location.com/
- http://www.ip2location.com/
- http://www.maxmind.com/
- http://www.maxmind.com/
#5
1
If you don't want to use an API like perhaps hostip.info, then I'd suggest subscribing to maxmind and running a host lookup database locally.
如果您不想使用像hostip.info那样的API,那么我建议订阅maxmind并在本地运行主机查找数据库。
#6
1
ip2cc - Lookup country and Russia region by IP address Python module with script to create database from up-to-date official data.
ip2cc - 通过IP地址查找国家和俄罗斯地区Python模块,使用脚本从最新的官方数据创建数据库。
This Python
utility loads (as frequently as you like) up-to-date information from Regional Internet Registry sites (arin
, ripencc
, apnic
, lacnic
, afrinic
), as shown in the source:
此Python实用程序会加载(尽可能频繁地)来自地区Internet注册站点(arin,ripencc,apnic,lacnic,afrinic)的最新信息,如源代码所示:
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)
Once the data is loaded, queries can be answered offline and very quickly. Can be easily modified to directly answer the original question, or used from the command line to return the country an IP address
belongs to.
加载数据后,可以离线并非常快速地回答查询。可以轻松修改以直接回答原始问题,或者从命令行使用返回国家/地区所属的IP地址。
#7
1
Another service you could use is my own, http://ipinfo.io, which returns location, organization and other information:
您可以使用的另一项服务是我自己的http://ipinfo.io,它返回位置,组织和其他信息:
$ 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
}
See http://ipinfo.io/developers for more information.
有关更多信息,请参阅http://ipinfo.io/developers。
#8
0
Here's how to do this with https://ipdata.co
以下是使用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
}
}⏎
#9
0
For offline database, you can get the free IP2Location LITE DB1
对于脱机数据库,您可以获得免费的IP2Location LITE DB1
To create the table
要创建表
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
To import the data
要导入数据
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
For the FMT file
对于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
The first line of the FMT code indicates the version of bcp. Please change the version as according to your MS-SQL installed.
FMT代码的第一行表示bcp的版本。请根据您安装的MS-SQL更改版本。
SQL Server 2016 12.0
SQL Server 2016 12.0
SQL Server 2014 12.0
SQL Server 2014 12.0
SQL Server 2012 11.0
SQL Server 2012 11.0
SQL Server 2008/2008 R2 10.0
SQL Server 2008/2008 R2 10.0
SQL Server 2005 9.0
SQL Server 2005 9.0
SQL Server 2000 8.0
SQL Server 2000 8.0
SQL Server 7.0 7.0
SQL Server 7.0 7.0
SQL Server 6.5 6.5
SQL Server 6.5 6.5
C# code to query MSSQL
用于查询MSSQL的C#代码
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();
}
}
}
#1
25
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.
您可以在项目中使用此SQL数据来确定:IP地址地理定位SQL数据库。下载该数据并将其导入数据库以在本地运行检查。
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:
或者您可以使用他们的免费API返回包含国家/地区代码和国家/地区名称的XML。您将使用您要检查的IP地址向以下URL发出请求,如下例所示:
http://ipinfodb.com/ip_query_country.php?ip=74.125.45.100
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>
#2
3
Just a simple API call e.g. https://ipapi.co/8.8.8.8/country/
只是简单的API调用,例如https://ipapi.co/8.8.8.8/country/
US
我们
Here's a C# example with working fiddle :
这是一个带工作小提琴的C#示例:
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());
}
}
#3
2
you can ask google to do it for you.
你可以请谷歌为你做这件事。
- http://googlecode.blogspot.com/2008/08/two-new-ways-to-location-enable-your.html
- http://googlecode.blogspot.com/2008/08/two-new-ways-to-location-enable-your.html
there are also services that you can pay for you want:
您还可以支付以下服务:
- http://www.ip2location.com/
- http://www.ip2location.com/
- http://www.maxmind.com/
- http://www.maxmind.com/
#4
#5
1
If you don't want to use an API like perhaps hostip.info, then I'd suggest subscribing to maxmind and running a host lookup database locally.
如果您不想使用像hostip.info那样的API,那么我建议订阅maxmind并在本地运行主机查找数据库。
#6
1
ip2cc - Lookup country and Russia region by IP address Python module with script to create database from up-to-date official data.
ip2cc - 通过IP地址查找国家和俄罗斯地区Python模块,使用脚本从最新的官方数据创建数据库。
This Python
utility loads (as frequently as you like) up-to-date information from Regional Internet Registry sites (arin
, ripencc
, apnic
, lacnic
, afrinic
), as shown in the source:
此Python实用程序会加载(尽可能频繁地)来自地区Internet注册站点(arin,ripencc,apnic,lacnic,afrinic)的最新信息,如源代码所示:
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)
Once the data is loaded, queries can be answered offline and very quickly. Can be easily modified to directly answer the original question, or used from the command line to return the country an IP address
belongs to.
加载数据后,可以离线并非常快速地回答查询。可以轻松修改以直接回答原始问题,或者从命令行使用返回国家/地区所属的IP地址。
#7
1
Another service you could use is my own, http://ipinfo.io, which returns location, organization and other information:
您可以使用的另一项服务是我自己的http://ipinfo.io,它返回位置,组织和其他信息:
$ 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
}
See http://ipinfo.io/developers for more information.
有关更多信息,请参阅http://ipinfo.io/developers。
#8
0
Here's how to do this with https://ipdata.co
以下是使用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
}
}⏎
#9
0
For offline database, you can get the free IP2Location LITE DB1
对于脱机数据库,您可以获得免费的IP2Location LITE DB1
To create the table
要创建表
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
To import the data
要导入数据
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
For the FMT file
对于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
The first line of the FMT code indicates the version of bcp. Please change the version as according to your MS-SQL installed.
FMT代码的第一行表示bcp的版本。请根据您安装的MS-SQL更改版本。
SQL Server 2016 12.0
SQL Server 2016 12.0
SQL Server 2014 12.0
SQL Server 2014 12.0
SQL Server 2012 11.0
SQL Server 2012 11.0
SQL Server 2008/2008 R2 10.0
SQL Server 2008/2008 R2 10.0
SQL Server 2005 9.0
SQL Server 2005 9.0
SQL Server 2000 8.0
SQL Server 2000 8.0
SQL Server 7.0 7.0
SQL Server 7.0 7.0
SQL Server 6.5 6.5
SQL Server 6.5 6.5
C# code to query MSSQL
用于查询MSSQL的C#代码
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();
}
}
}