使用 ip2region 或 geoip2 根据用户ip获取用户省市
这两种方式都不能获取到区县级别
在 简单的测试 中感觉 geoip 不如 ip2region 精确,而且 ip2region 的数据库文件也要小一些
ip2region
官方地址: https://github.com/lionsoul2014/ip2region/tree/master
在pom中引入内容
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
代码示例
import org.lionsoul.ip2region.xdb.Searcher;
public String testIp2Region() {
// 测试的ip地址
String ip = "112.13.53.138";
// 获取resource下的xdb文件
String dbPath = Object.class.getResource("/ip2region.xdb").getPath();
// 1、从 dbPath 加载整个 xdb 到内存。
byte[] cBuff;
try {
cBuff = Searcher.loadContentFromFile(dbPath);
} catch (Exception e) {
System.out.printf("failed to load content from `%s`: %s\n", dbPath, e);
return null;
}
// 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
Searcher searcher;
try {
searcher = Searcher.newWithBuffer(cBuff);
} catch (Exception e) {
System.out.printf("failed to create content cached searcher: %s\n", e);
return null;
}
// 3、查询
try {
// 结果的固定格式 国家|区域|省份|城市|ISP 缺省补0
// 这里区域没有获取到 补了0
String region = searcher.search(ip);
System.out.printf(region); // 中国|0|浙江省|温州市|移动
return region;
} catch (Exception e) {
System.out.printf("failed to search(%s): %s\n", ip, e);
}
return null;
}
geoip2
官方下载地址需要注册: https://www.maxmind.com/en/accounts/current/geoip/downloads
我是在这里下载的: https://github.com/P3TERX/GeoLite.mmdb?tab=readme-ov-file
在pom中引入内容
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.12.0</version>
</dependency>
代码示例
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
public void testGeoip() {
// 测试ip
String ip = "112.13.53.138";
// GeoIP2-City 数据库文件
String dbPath = Object.class.getResource("/GeoLite2-City.mmdb").getPath();
File database = new File(dbPath);
// 创建 DatabaseReader对象
try {
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode());
System.out.println(country.getName()); // 国家
System.out.println(country.getNames().get("zh-CN")); // 国家中文
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getIsoCode());
System.out.println(subdivision.getName()); // 省市
System.out.println(subdivision.getNames().get("zh-CN"));// 省市中文
City city = response.getCity();
System.out.println(city.getName()); // 城市
System.out.println(city.getNames().get("zh-CN"));// 城市中文
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 纬度
System.out.println(location.getLongitude()); // 经度
} catch (Exception e) {
e.printStackTrace();
}
}
比较IP2Region与GeoIP2:基于地理位置的用户IP详细定位,
2352

被折叠的 条评论
为什么被折叠?



