前言
在開發中,我們需要記錄關於登入者的 IP 和位置資訊,可以透過 ip2region 來實現!
比如說:
- qq,gitee 等 我們在異地登入時,會提醒我們帳號異地登入!
- 外送等軟體,需要地理位置,如果我們的 GPS 關閉,也可以根據 IP 分析地理位置等
簡介
ip2region - 準確率 99.9% 的離線 IP 位址定位庫,0.0x 毫秒級查詢,ip2region.db 資料庫只有數 MB,提供了 Java, PHP, C, Python, Nodejs, Golang, C# 等查詢綁定和 Binary, B 樹, 記憶體三種查詢演算法。每條 IP 資料段都固定了格式:
- 城市 Id|國家|區域|省份|城市|ISP_
- github 位址:https://github.com/lionsoul2014/ip2region
使用
- nuget 安裝
Install-Package IP2Region
- 下載 ip2region.db
git clone https://github.com/lionsoul2014/ip2region.git
然後到 data/ 資料夾下面找到 ip2region.db 複製到專案 resources 下
使用就很簡單了,程式碼就一行
static void Main(string[] args)
{
using (var _search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db"))
{
Console.WriteLine(_search.MemorySearch("183.129.193.166").Region);
Console.Read();
}
}
總結
文章來源於即興發揮,雖然我工作中現在還沒遇到這種需求,但是了解一下總歸是有好處的,歡迎大家留言討論!