1.引入geoip maven库
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.16.1</version>
</dependency>
2.下载geoip 城市库
下载地址:https://www.maxmind.com/en/accounts/637922/geoip/downloads
3.添加通过ip获取国家城市方法
public static CityResponse getIpCountryAndCity(String ip) {
InputStream resourceAsStream = IpUtil.class.getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
try {
DatabaseReader reader = new DatabaseReader.Builder(resourceAsStream).build();
InetAddress ipAddress = InetAddress.getByName(ip);
return reader.city(ipAddress);
} catch (IOException | GeoIp2Exception e) {
e.printStackTrace();
}
return null;
}
项目源码:https://github.com/mingtao66/ip
上次更新时间 13 3 月, 2023 at 09:59 上午