需要ip2region.db文件,可以前往github下载
public class IpUtil {
private static DbSearcher searcher;
private static Method method;
public static String getIpAddress(HttpServletRequest request) {
String ipAddress = request.getHeader("X-Real-IP");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("x-forwarded-for");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("getIpAddress exception:", e);
}
assert inet != null;
ipAddress = inet.getHostAddress();
}
}
return StringUtils.substringBefore(ipAddress, ",");
}
@PostConstruct
private void initIp2regionResource() throws Exception {
InputStream inputStream = new ClassPathResource("/ip/ip2region.db").getInputStream();
byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
DbConfig dbConfig = new DbConfig();
searcher = new DbSearcher(dbConfig, dbBinStr);
method = searcher.getClass().getMethod("memorySearch", String.class);
}
public static String getIpSource(String ipAddress) {
if (ipAddress == null || !Util.isIpAddress(ipAddress)) {
log.error("Error: Invalid ip address");
return "";
}
try {
DataBlock dataBlock = (DataBlock) method.invoke(searcher, ipAddress);
String ipInfo = dataBlock.getRegion();
if (!StringUtils.isEmpty(ipInfo)) {
ipInfo = ipInfo.replace("|0", "");
ipInfo = ipInfo.replace("0|", "");
return ipInfo;
}
} catch (Exception e) {
log.error("getCityInfo exception:", e);
}
return "";
}
public static String getIpProvince(String ipSource) {
if (StringUtils.isBlank(ipSource)) {
return CommonConstant.UNKNOWN;
}
String[] strings = ipSource.split("\\|");
if (strings.length > 1 && strings[1].endsWith("省")) {
return StringUtils.substringBefore(strings[1], "省");
}
return strings[0];
}
public static UserAgent getUserAgent(HttpServletRequest request) {
return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
}
欢迎访问我的博客网站:
www.yqiu.top文章来源:https://www.toymoban.com/news/detail-836965.html
文章来源地址https://www.toymoban.com/news/detail-836965.html
到了这里,关于java获取ip地址以及ip归属地工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!