根據IP獲取城市-Java調用“ip2region”地址庫實例

根據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“
     
    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.  
  3. import java.io.File;
  4. import java.lang.reflect.Method;
  5.  
  6. import org.lionsoul.ip2region.DataBlock;
  7. import org.lionsoul.ip2region.DbConfig;
  8. import org.lionsoul.ip2region.DbSearcher;
  9. import org.lionsoul.ip2region.Util;
  10.  
  11. public class IPUtil {
  12.  
  13. public static String getCityInfo(String ip){
  14.  
  15. //db
  16. String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
  17.  
  18. File file = new File(dbPath);
  19. if ( file.exists() == false ) {
  20. System.out.println("Error: Invalid ip2region.db file");
  21. }
  22.  
  23. //查詢算法
  24. int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
  25. //DbSearcher.BINARY_ALGORITHM //Binary
  26. //DbSearcher.MEMORY_ALGORITYM //Memory
  27. try {
  28. DbConfig config = new DbConfig();
  29. DbSearcher searcher = new DbSearcher(config, dbPath);
  30.  
  31. //define the method
  32. Method method = null;
  33. switch ( algorithm )
  34. {
  35. case DbSearcher.BTREE_ALGORITHM:
  36. method = searcher.getClass().getMethod("btreeSearch", String.class);
  37. break;
  38. case DbSearcher.BINARY_ALGORITHM:
  39. method = searcher.getClass().getMethod("binarySearch", String.class);
  40. break;
  41. case DbSearcher.MEMORY_ALGORITYM:
  42. method = searcher.getClass().getMethod("memorySearch", String.class);
  43. break;
  44. }
  45.  
  46. DataBlock dataBlock = null;
  47. if ( Util.isIpAddress(ip) == false ) {
  48. System.out.println("Error: Invalid ip address");
  49. }
  50.  
  51. dataBlock = (DataBlock) method.invoke(searcher, ip);
  52.  
  53. return dataBlock.getRegion();
  54.  
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58.  
  59. return null;
  60. }
  61.  
  62.  
  63. public static void main(String[] args) throws Exception{
  64. System.err.println(getCityInfo("220.248.12.158"));
  65. }
  66. }

運行結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章