ip2region2.6.5 工具类
下载离线库
data/ip2region.xdb · 狮子的魂/ip2region - 码云 - 开源中国 (gitee.com)
放到资源目录下面
引入 maven 坐标
<!-- ip2region -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.6.5</version>
</dependency>
代码
@Slf4j
@Component
public class IpAddressUtils {
private static Searcher searcher;
public static String getIpAddress() {
return getIpAddress(ServletUtils.getHttpServletRequest());
}
/**
* 在Nginx等代理之后获取用户真实IP地址
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
if (request == null) {
return null;
}
String ip = request.getHeader("x-forwarded-for");
if (isIpaddress(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (isIpaddress(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (isIpaddress(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (isIpaddress(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (isIpaddress(ip)) {
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
//根据网卡取本机配置的IP
try {
InetAddress inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (UnknownHostException e) {
log.error("getIpAddress exception:", e);
}
}
}
return StringUtils.substringBefore(ip, ",");
}
public static boolean isIpaddress(String ip) {
return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
}
/**
* 获取IP地址
*
* @return 本地IP地址
*/
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "127.0.0.1";
}
/**
* 获取主机名
*
* @return 本地主机名
*/
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "未知";
}
/**
* 根据ip从 ip2region.db 中获取地理位置
* @param ip
* @return
*/
public static String getCityInfo(String ip) {
try {
return searcher.search(ip);
} catch (Exception e) {
log.info("failed to search(%s): %s\n", ip, e);
}
return null;
}
/**
* 在服务启动时加载 ip2region.db 到内存中
* 解决打包jar后找不到 ip2region.db 的问题
*
* @throws Exception 出现异常应该直接抛出终止程序启动,避免后续invoke时出现更多错误
*/
@PostConstruct
private static void initIp2regionResource() {
try {
InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
// 创建一个完全基于内存的查询对象
searcher = Searcher.newWithBuffer(dbBinStr);
} catch (Exception e) {
log.info("failed to create content cached searcher: %s\n", e);
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
initIp2regionResource();
System.out.println(getCityInfo("120.36.213.176"));
}
}
运行测试结果: