当前位置:网站首页>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 .
边栏推荐
- What is the difference between 14Cr1MoR container plate and 14Cr1MoR (H)? Chemical composition and performance analysis of 14Cr1MoR
- word 退格键删除不了选中文本,只能按delete
- LeetCode 1658. Minimum operand to reduce x to 0
- Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
- Network security web penetration technology
- Idea configuration plug-in
- There are several APIs of airtest and poco that are easy to use wrong in "super". See if you have encountered them
- Simulink oscilloscope data is imported into Matlab and drawn
- 线程池执行定时任务
- Arduino esp32: overall framework of lvgl project (I)
猜你喜欢

The word backspace key cannot delete the selected text, so you can only press Delete

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

What material is sa537cl1? Sa537cl1 corresponds to the national standard material

What material is 12cr1movr? Chemical property analysis of pressure vessel steel plate 12cr1movr

Visual SLAM algorithms: a survey from 2010 to 2016

Daily code 300 lines learning notes day 10

Arduino esp32: overall framework of lvgl project (I)

于文文、胡夏等明星带你玩转派对 皮皮APP点燃你的夏日

Mysql 单表字段重复数据取最新一条sql语句

What is the material of 13mnnimor? 13mnnimor steel plate for medium and low temperature pressure vessels
随机推荐
AcWing 第58 场周赛
LeetCode 1657. Determine whether the two strings are close
Is it safe to open a stock account by mobile registration? Does it need money to open an account
Client does not support authentication protocol requested by server; consider upgrading MySQL client
LeetCode 1658. Minimum operand to reduce x to 0
Processing strategy of message queue message loss and repeated message sending
Le zèbre a été identifié comme un chien, et la cause de l'erreur d'AI a été trouvée par Stanford
Daily code 300 lines learning notes day 10
Mysql database DDL and DML
[combinatorics] non descending path problem (number of non descending paths with constraints)
NSQ source code installation and operation process
Kotlin学习快速入门(7)——扩展的妙用
【剑指 Offer】58 - II. 左旋转字符串
Visual SLAM algorithms: a survey from 2010 to 2016
QT serial port UI design and solution to display Chinese garbled code
浅谈拉格朗日插值及其应用
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Using optimistic lock and pessimistic lock in MySQL to realize distributed lock
智慧之道(知行合一)
RF Analyze Demo搭建 Step by Step