添加pom依赖
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.1</version>
</dependency>
获取IP地址
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
if (ip.split(",").length > 1) {
ip = ip.split(",")[0];
}
return ip;
}
获取IP的信息(去官网下载GeoLite2-City.mmdb文件也可以到我的分享网盘中获取)
官方下载地址:【http://dev.maxmind.com/geoip/geoip2/geolite2/】
我的链接:https://pan.baidu.com/s/1qYmoMBBy1MZS24PNRlJ_6g
提取码:auic
public static String[] geoip2(String ip, String url){
File file;
// 创建 GeoLite2 数据库[GeoLite2-City.mmdb是关键文件(若该文件不存在则IP会解析失败)]
file = new File(url + "GeoLite2-City.mmdb");
if (!file.exists()) {
logger.debug("Error: Invalid GeoLite2-City.mmdb file, filePath:" + file.getPath());
return null;
}
// 读取数据库内容
DatabaseReader reader = null;
try {
reader = new DatabaseReader.Builder(file).build();
//解析IP地址
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
String country = response.getCountry().getNames().get("zh-CN");
// 获取省份
String sheng = response.getMostSpecificSubdivision().getNames().get("zh-CN");
//查询不到时保持与ip2region方式的返回结果一致
if (sheng == null){
sheng = "0";
}
// 获取城市
String shi = response.getCity().getNames().get("zh-CN");
if (shi == null){
shi = "0";
}
String[] resu = {sheng,shi};
return resu;
} catch (IOException | GeoIp2Exception e) {
e.printStackTrace();
return null;
}
}
执行测试
@PostMapping("/getResolveIP")
public String[] getResolveIP(HttpServletRequest request){
//获取用户IP
String ip = getIpAddr(request);
//解析IP信息
return geoip2(ip,"自己的 GeoLite2-City.mmdb 文件路径");
}