python開發ip2region 離線IP庫地址檔案
一、專案簡介
ip2region - 離線的ip地址查詢庫,ip到地區的對映庫,提供二進位制,B樹,記憶體搜尋三種查詢演算法,查詢速度非常快。
支援Java,PHP,C,Python,Nodejs,Golang,C#等語言,本文以Python為例
下載地址:https://github.com/lionsoul2014/ip2region
專案測試程式碼:本例中ip2region.db與testSearcher.py在同一個目錄
D:\code\ip2region\binding\python>python testSearcher.py ip2region.db
initializing b-tree...
+----------------------------------+
| ip2region test program |
| Author: [email protected]. |
| Type 'quit' to exit program |
+----------------------------------+
ip2region>> 45.15.11.150
0|中國|0|香港|0|0 in 98.978027 millseconds
ip2region>> 206.189.50.204
14|新加坡|0|0|0|0 in 0.000000 millseconds
ip2region>> 106.13.211.178
2140|中國|0|廣東省|廣州市|電信 in 0.000000 millseconds
ip2region>>
二、詳細分析
python 示例程式碼:testSearcher.py、ip2Region.py、benchmark.py
離線程式碼庫ip2region.db在data目錄下。
執行test.py示例如下,生成結果檔案result.csv。
result.csv
輸入檔案是ip.txt。
三、程式碼test.py
import time from ip2Region import Ip2Region import csv def testSearch(ip_s): dbFile = "ip2region.db" searcher = Ip2Region(dbFile) try: print("開始檢測:",(ip_s)) sTime = time.time() * 1000 data = searcher.binarySearch(ip_s) # elif algorithm == "memory": #data = searcher.memorySearch(line) # else: # data = searcher.btreeSearch(line) eTime = time.time() * 1000 ip_info = ("%s|%s|%s" % (ip_s, data["city_id"], data["region"].decode('utf-8'))) print("檢測完成:" + ip_info) return ip_info except Exception as e: print("[Error]: %s" % e) searcher.close() def all_in(): c = open("result.csv","w", newline="") writer=csv.writer(c) title = ['源ip', '國家', '省市','運營商'] writer.writerow(title) with open('ip.txt' ,'r') as file: for line in file.readlines(): ip = line.strip() try: data = testSearch(ip) ct = data.split('|')[2].strip() pv = data.split('|')[4].strip() city = data.split('|')[5].strip() yys = data.split('|')[6].strip() if ct == "0": print("地址庫中未找到對應的IP歸屬地,請更新地址庫或者確定ip準確性!") writer.writerow([ip, "/", "/","/"]) else: if pv == "0": print("省市查詢為空!") writer.writerow([ip, ct, "/","/"]) else: if city == "0": writer.writerow([ip, ct, pv + "-" + "///","/"]) else: if yys == "0": writer.writerow([ip, ct, pv + "-" + city,"/"]) else: writer.writerow([ip, ct, pv + "-" + city,yys]) except Exception as e: print("[Error]: %s" % e) writer.writerow([ip,"檢測異常,請手動檢測!"]) c.close() if __name__ == "__main__": all_in()