package com.xxx.xxx.common.util;
import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* 地址判断
*
* 使用 ip2region 插件(来自 https://gitee.com/lionsoul/ip2region)
*
* 根据 IP 取得城市地址
*/
public class AddressUtils {
/**
* 根据 IP 取得城市地址
* @param ip
* @return 城市名称 或 null
*/
public static String getCityInfo(String ip) {
if (ip == null || !Util.isIpAddress(ip)) {
System.out.println("Error: Invalid ip address");
return null;
}
DbSearcher searcher = null;
try {
String dbPath = AddressUtils.class.getResource("/ip2region/ip2region.db").getPath();
File file = new File(dbPath);
if (!file.exists()) {
String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
dbPath = tmpDir + "ip.db";
file = new File(dbPath);
FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtils.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db")), file);
//FileUtils.copyInputStreamToFile(AddressUtils.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db"), file);
}
int algorithm = DbSearcher.BTREE_ALGORITHM;
DbConfig config = new DbConfig();
searcher = new DbSearcher(config, dbPath);
Method method = null;
switch (algorithm) {
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock = null;
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
System.out.println(e.getMessage());
//log.error("获取IP地址失败,{}", e.getMessage());
} finally {
if (searcher != null) {
try {
searcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
根据 IP取得城市地址
最新推荐文章于 2024-05-06 18:16:21 发布