原鏈接:根據IP獲取城市-Java調用“ip2region”地址庫實例-媽媽再也不用擔心我的ip地址定位啦
- ip2region
准確率99.9%的ip地址定位庫,0.0x毫秒級查詢,數據庫文件大小只有1.5M,提供了java,php,c,python,nodejs,golang查詢綁定和Binary,B樹,內存三種查詢算法
github地址:https://github.com/lionsoul2014/ip2region
解壓目錄如下圖:
- 新建java項目,導入binding/java下的代碼,並復制”data/ip2region.db”到“src目錄
- 創建“IPUtil”.java ,內容參考”org.lionsoul.ip2region.test.TestSearcher.java“
package com.xx; import java.io.File; import java.lang.reflect.Method; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import org.lionsoul.ip2region.Util; public class IPUtil { public static String getCityInfo(String ip){ //db String dbPath = IPUtil.class.getResource("/ip2region.db").getPath(); File file = new File(dbPath); if ( file.exists() == false ) { System.out.println("Error: Invalid ip2region.db file"); } //查詢算法 int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree //DbSearcher.BINARY_ALGORITHM //Binary //DbSearcher.MEMORY_ALGORITYM //Memory try { DbConfig config = new DbConfig(); DbSearcher searcher = new DbSearcher(config, dbPath); //define the method Method method = null; switch ( algorithm ) { case DbSearcher.BTREE_ALGORITHM: method = searcher.getClass().getMethod("btreeSearch", String.class); break; case DbSearcher.BINARY_ALGORITHM: method = searcher.getClass().getMethod("binarySearch", String.class); break; case DbSearcher.MEMORY_ALGORITYM: method = searcher.getClass().getMethod("memorySearch", String.class); break; } DataBlock dataBlock = null; if ( Util.isIpAddress(ip) == false ) { System.out.println("Error: Invalid ip address"); } dataBlock = (DataBlock) method.invoke(searcher, ip); return dataBlock.getRegion(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws Exception{ System.err.println(getCityInfo("220.248.12.158")); } }
運行結果如下:
見鬼網 微信公眾平台 : “ 見鬼網”(ID:faceghost) 歡迎關注~