Java 根據 IP 地址來獲取 位置 -- 使用 ip2region
阿新 • • 發佈:2018-12-11
首先在 maven 裡面引入 ip2region :
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7</version>
</dependency>
然後下載 IP庫 ip2region.db: https://gitee.com/lionsoul/ip2region/tree/master/data
下載過程可能需要註冊 碼雲,碼雲相當於中國的 GitHub 有必要註冊下.
下載解壓後只需要 data 目錄下的 ip2region.db 就可以了 .
把 ip2region.db 複製到 maven 專案的 resources 目錄下.
然後具體實現,可以把以下程式碼封裝成方法:
public class Ip2RegionTest { public static void main(String[] args){ //ip String ip="220.248.12.158"; // 判斷是否為IP地址 (可用) //boolean isIpAddress = Util.isIpAddress(ip); //ip和long互轉 (可用) //long ipLong = Util.ip2long(ip); //String strIp = Util.long2ip(ipLong); //根據ip進行位置資訊搜尋 DbConfig config = new DbConfig(); //獲取ip庫的位置(放在src下)(直接通過測試類獲取檔案Ip2RegionTest為測試類) String dbfile = Ip2RegionTest.class.getResource("/ip2region.db").getPath(); DbSearcher searcher = new DbSearcher(config, dbfile); //採用Btree搜尋 DataBlock block = searcher.btreeSearch(ip); //列印位置資訊(格式:國家|大區|省份|城市|運營商) System.out.println(block.getRegion()); } }
還有一種實現方法如下:
此內容參考了 ip2region原始碼的 : org.lionsoul.ip2region.test.TestSearcher.java
package com.test; 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")); } }
如果對下載後的原始碼 感興趣,可以仿照此篇文章的做法: Java - 根據IP獲取城市
把 ip2region\binding\java 下的檔案 複製到專案中,然後再 把 ip2region.db 複製到對應的目錄
其中的 實現方法是 參考 原始碼中的 案例 org.lionsoul.ip2region.test.TestSearcher.java