当前位置:网站首页>How to judge the region of an IP through C?
How to judge the region of an IP through C?
2022-07-03 16:47:00 【Dotnet cross platform】
Consultation area
RC1140
How to use C# Judge a certain IP Region ? So I can make statistics easily .
Answer area
Jaimes
With the help of a third party API Interface , Refer to the website :https://ipapi.co/8.8.8.8/country/ , C# The code is as follows :
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());
}
}Vlam
There is an offline IP Regional Library , It can realize complete offline query , Download link :https://lite.ip2location.com/database/ip-country
Create a table and import
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
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'
)
GOCode query
We have the database , Next we can use C# The query .
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();
}
}
}Comment area
I didn't expect an offline version IP Address base , This is good , To study the .
边栏推荐
- Mysql 将逗号隔开的属性字段数据由列转行
- Explore Netease's large-scale automated testing solutions see here see here
- What is the pledge pool and how to pledge?
- Golang anonymous function use
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- Capacités nécessaires à l'analyse des données
- Network security web penetration technology
- 面试之 top k问题
- Shentong express expects an annual loss of nearly 1billion
- CC2530 common registers
猜你喜欢

Cocos Creator 2.x 自动打包(构建 + 编译)

MySQL single table field duplicate data takes the latest SQL statement

PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug

关于视觉SLAM的最先进技术的调查-A survey of state-of-the-art on visual SLAM

爱可可AI前沿推介(7.3)

What is the maximum number of concurrent TCP connections for a server? 65535?

Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..

What kind of material is 14Cr1MoR? Analysis of chemical composition and mechanical properties of 14Cr1MoR

Mysql 将逗号隔开的属性字段数据由列转行

消息队列消息丢失和消息重复发送的处理策略
随机推荐
Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
Difference between JSON and bson
Acwing game 58
Google Earth engine (GEE) - daymet v4: daily surface weather data set (1000m resolution) including data acquisition methods for each day
Unreal_ Datatable implements ID self increment and sets rowname
Network security web penetration technology
PHP converts a one-dimensional array into a two-dimensional array
Pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
【剑指 Offer 】57 - II. 和为s的连续正数序列
Simulink oscilloscope data is imported into Matlab and drawn
Netease UI automation test exploration: airtest+poco
What is the material of sa302grc? American standard container plate sa302grc chemical composition
Capacités nécessaires à l'analyse des données
Extraction of the same pointcut
CC2530 common registers for port initialization
浅谈拉格朗日插值及其应用
比亚迪、长城混动市场再“聚首”
Interviewer: how does the JVM allocate and recycle off heap memory
Nifi from introduction to practice (nanny level tutorial) - flow
8个酷炫可视化图表,快速写出老板爱看的可视化分析报告