1.准备ip2region.bd文件
2.添加pom依赖
<dependency> <groupId>org.lionsoul</groupId> <artifactId>ip2region</artifactId> <version>1.7.2</version> </dependency>
3.编写util
public static String getIpInfo(String ip ,int algorithm) { if (!Util.isIpAddress(ip)) { System.out.println("无效的ip地址"); return null; } File file = new File("D://ip2region.db"); if (!file.exists()) { return null; } try { DbConfig config = new DbConfig(); DbSearcher searcher = new DbSearcher(config, file.getPath()); DataBlock block; switch ( algorithm ) { case DbSearcher.BTREE_ALGORITHM: block = searcher.btreeSearch(ip); break; case DbSearcher.BINARY_ALGORITHM: block = searcher.binarySearch(ip); break; case DbSearcher.MEMORY_ALGORITYM: block = searcher.memorySearch(ip); break; default: return null; } return block.getRegion(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { System.out.println(getIpInfo("27.158.41.235",1)); }