当我们知道用户ip的情况下,需要统计用户所属的国家/省份/城市等信息。
这时可以用开源的Geoip2 避免重复造轮子。
github地址:https://github.com/maxmind/GeoIP2-java
获取代码中 GeoLite2-City.mmdb 数据的官网(需要先登录注册):https://www.maxmind.com/en/accounts/746301/geoip/downloads
离线获取ip信息需要数据库信息,数据库可以在官网下载。
maxmind数据库官网下载地址:https://www.maxmind.com/en/accounts/746301/geoip/downloads
下载之前需要先注册登录。然后找到如下图位置点击下载即可。
GeoLite2-City.mmdb附件信息:

pom添加如下引用(如果引用3.xx提示类错误的话,可以换成2.xx版本):
<dependency>
<groupId>com.maxmind.geoip2groupId>
<artifactId>geoip2artifactId>
<version>2.16.1version>
dependency>
简单开发
public class IpUtil {
private static final String ip2cityDataPath = "D:\\GeoLite2CityData\\GeoLite2-City_20220726\\GeoLite2-City.mmdb";
public static void main(String[] args) {
String ip = "47.111.xxx.xxx";
try (DatabaseReader dr = new DatabaseReader.Builder(new File(ip2cityDataPath)).build()) {
final CityResponse response = dr.city(InetAddress.getByName(ip));
// 获取国家信息
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'CN'
System.out.println(country.getName()); // 'China'
System.out.println(country.getNames().get("zh-CN")); // '中国'
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); //Zhejiang
System.out.println(subdivision.getIsoCode()); // ZJ
System.out.println(subdivision.getNames().get("zh-CN")); // 浙江省
// 获取城市
City city = response.getCity();
System.out.println(city.getName()); // Hangzhou
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // 'null'
System.out.println(city.getNames().get("zh-CN")); // 杭州
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 30.2994
} catch (Exception io) {
io.printStackTrace();
}
}
}