1、加入依赖

2、下载离线包

https://github.com/lionsoul2014/ip2region

3、代码

  // 并发使用时,每个线程需要创建一个独立的 searcher 对象单独使用。

  //  创建 searcher 对象 (修改为离线库路径)
  String dbPath = "D:\\devtool\\ip2region-master\\data\\ip2region.xdb";
  Searcher searcher = null;
  try {
      searcher = Searcher.newWithFileOnly(dbPath);
      // 获取本机IP地址
      InetAddress localhost = InetAddress.getByName("localhost");

      // 获取指定域名的IP地址
      InetAddress google = InetAddress.getByName("www.google.com");

      String ip = localhost.getHostAddress();
      ip = google.getHostAddress();

      long sTime = System.nanoTime();
      String region = searcher.search(ip);
      long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
      System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
  } catch (Exception e) {
   	 e.printStackTrace();
  }finally {
      // 关闭资源
      searcher.close();
  }