1、加入依赖
x
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
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();
}