视频网站开发平台,线上兼职,个人网站可以做营销吗,网站开发的工作流程咨询区 RC1140如何通过 C# 判断某个 IP 所属的地区#xff1f;这样我就可以方便统计。回答区 Jaimes可以借助第三方API接口#xff0c;参考网址#xff1a;https://ipapi.co/8.8.8.8/country/ #xff0c; C# 代码如下#xff1a;using System;
using System.Net;
using S… 咨询区 RC1140如何通过 C# 判断某个 IP 所属的地区这样我就可以方便统计。回答区 Jaimes可以借助第三方API接口参考网址https://ipapi.co/8.8.8.8/country/ 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());}
}Vlam有一个离线的 IP地区库可以实现完全的离线查询下载链接https://lite.ip2location.com/database/ip-country创建表并导入CREATE DATABASE ip2location
GOUSE ip2location
GOCREATE 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]
GOCREATE INDEX [ip_from] ON [ip2location].[dbo].[ip2location_db1]([ip_from]) ON [PRIMARY]
GOCREATE INDEX [ip_to] ON [ip2location].[dbo].[ip2location_db1]([ip_to]) ON [PRIMARY]
GOBULK INSERT [ip2location].[dbo].[ip2location_db1]FROM C:\[path to your CSV file]\IP2LOCATION-LITE-DB1.CSVWITH(FORMATFILE C:\[path to your DB1.FMT file]\DB1.FMT)
GO代码查询数据库有了接下来就可以用 C# 查询了。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(Serveryourserver;Databaseyourdatabase;User Idyouruserid;Passwordyourpassword;);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) {Listbyte byteList new Listbyte(byteArr);byteList.Reverse();byteArr byteList.ToArray();}}
}点评区 没想到还有离线版本的 IP地址库这个不错学习了。