IP转地址

官方链接:

参考文章:

简介

ip2region v2.0 - 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb 数据生成和查询客户端实现。每个 ip 数据段的 region 信息都固定了格式:国家|区域|省份|城市|ISP(网络服务提供商)

使用

获取离线包

从网站上获取ip2region离线包,并将ip2region.xdb放在resource目录下

获取离线包

导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- ip2region依赖(必须) -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.6.5</version>
</dependency>

<!-- hutool依赖(非必须) -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4</version>
</dependency>

简单使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import cn.hutool.core.io.resource.ResourceUtil;
import org.lionsoul.ip2region.xdb.Searcher;

public class Main {
public static void main(String[] args) {
// 使用hutool的ResourceUtil从resource目录下读取ip2region.xdb文件
byte[] bytes = ResourceUtil.readBytes("ip2region.xdb");
try {
// 创建一个完全基于内存的查询对象
Searcher searcher = Searcher.newWithBuffer(bytes);
// 查询ip,返回值:国家|区域|省份|城市|ISP(网络服务提供商)
System.out.println(searcher.search("1.2.3.4"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 控制台打印:
// 美国|0|华盛顿|0|谷歌

工具类封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import cn.hutool.core.io.resource.ResourceUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.lionsoul.ip2region.xdb.Searcher;
import javax.annotation.PostConstruct;

@Component
public final class IpUtils {

/**
* 一个完全基于内存的查询对象
*/
private static Searcher searcher;

/**
* 默认返回值
*/
private static final String UNKNOWN_ADDRESS = "UNKNOWN";

/**
* 初始化
*/
@PostConstruct
public static void init() {
try {
searcher = Searcher.newWithBuffer(ResourceUtil.readBytes("ip2region.xdb"));
} catch (Exception e) {
throw new RuntimeException("failed to create content cached searcher", e);
}
}

/**
* IP转地址
* @param ip ip
* @return 地址
*/
public static String ipToAddress(String ip) {
try {
return searcher.search(ip);
} catch (Exception e) {
return UNKNOWN_ADDRESS;
}
}
}