@Slf4j
public class IPUtils {
public static String getAddress(String ip) throws IOException {
if (Func.isBlank(ip)) {
return "";
}
InputStream inputStream = IPUtils.class.getResourceAsStream("/ip/ip2region.xdb");
if (Func.isNull(inputStream)) {
log.error("没有找到计算IP地址数据文件");
return "";
}
File file = new File("/ip/ip2regionCopy.xdb");
FileUtils.copyInputStreamToFile(inputStream, file);
String dbPathService = file.getPath();
Searcher searcher = null;
try {
searcher = Searcher.newWithFileOnly(dbPathService);
} catch (IOException e) {
log.info("初始化xdb数据文件错误" + e.getMessage());
}
log.info("服务路径:" + dbPathService);
String region = "";
try {
region = searcher.search(ip);
} catch (Exception e) {
throw new RuntimeException(e);
}
log.info(region);
String address = "";
try {
address = changeAddress(region);
} catch (Exception e) {
log.info("转换地址失败" + e.getMessage());
log.error(e.getMessage());
return "";
}
log.info("最后地址:" + address);
searcher.close();
inputStream.close();
log.info("起始---------------------------------------------------------");
return address;
}
private static String changeAddress(String region) {
StringBuilder address = new StringBuilder();
if (Func.isNoneBlank(region)) {
if (region.contains("内网IP")) {
return "";
}
List<String> areas = Arrays.asList(Func.split(region, "|"));
address.append(
Func.equals(areas.get(0), "0") ? "" : (areas.get(0) + "-")
).append(
Func.equals(areas.get(2), "0") ? "" : (areas.get(2) + "-")
).append(
Func.equals(areas.get(3), "0") ? "" : areas.get(3) + "-"
);
address = new StringBuilder(address.substring(0, address.length() - 1));
}
return address.toString();
}
}