根据IP获取城市-Java调用“ip2region”地址库实例

根据IP获取城市-Java调用“ip2region”地址库实例-妈妈再也不用担心我的ip地址定位啦

    ip2region

准确率99.9%的ip地址定位库,0.0x毫秒级查询,数据库文件大小只有1.5M,提供了java,php,c,python,nodejs,golang查询绑定和Binary,B树,内存三种查询算法

github地址:

    下载v1.3版本:

解压目录如下图:

    新建java项目,导入binding/java下的代码,并复制”data/ip2region.db”到“src目录
    创建“IPUtil”.java ,内容参考”org.lionsoul.ip2region.test.TestSearcher.java“ maven仓库地址 <dependency> <groupId>org.lionsoul</groupId> <artifactId>ip2region</artifactId> <version>1.7.2</version> </dependency> gradle compile group: org.lionsoul, name: ip2region, version: 1.7.2
 
  1. package com.xx;
  2. import java.io.File;
  3. import java.lang.reflect.Method;
  4. import org.lionsoul.ip2region.DataBlock;
  5. import org.lionsoul.ip2region.DbConfig;
  6. import org.lionsoul.ip2region.DbSearcher;
  7. import org.lionsoul.ip2region.Util;
  8. public class IPUtil {
  9. public static String getCityInfo(String ip){
  10. //db
  11. String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
  12. File file = new File(dbPath);
  13. if ( file.exists() == false ) {
  14. System.out.println("Error: Invalid ip2region.db file");
  15. }
  16. //查询算法
  17. int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
  18. //DbSearcher.BINARY_ALGORITHM //Binary
  19. //DbSearcher.MEMORY_ALGORITYM //Memory
  20. try {
  21. DbConfig config = new DbConfig();
  22. DbSearcher searcher = new DbSearcher(config, dbPath);
  23. //define the method
  24. Method method = null;
  25. switch ( algorithm )
  26. {
  27. case DbSearcher.BTREE_ALGORITHM:
  28. method = searcher.getClass().getMethod("btreeSearch", String.class);
  29. break;
  30. case DbSearcher.BINARY_ALGORITHM:
  31. method = searcher.getClass().getMethod("binarySearch", String.class);
  32. break;
  33. case DbSearcher.MEMORY_ALGORITYM:
  34. method = searcher.getClass().getMethod("memorySearch", String.class);
  35. break;
  36. }
  37. DataBlock dataBlock = null;
  38. if ( Util.isIpAddress(ip) == false ) {
  39. System.out.println("Error: Invalid ip address");
  40. }
  41. dataBlock = (DataBlock) method.invoke(searcher, ip);
  42. return dataBlock.getRegion();
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. return null;
  47. }
  48. public static void main(String[] args) throws Exception{
  49. System.err.println(getCityInfo("220.248.12.158"));
  50. }
  51. }

运行结果如下:

经验分享 程序员 微信小程序 职场和发展