工具类封装实战(二)ip工具类
【摘要】
private static final String UNKNOWN = "unknown"; //本地IP private static final String LOCAL_IP = "127.0.0.1"; //服务器IP private static String SERVER_IP = null; ...
-
private static final String UNKNOWN = "unknown";
-
//本地IP
-
private static final String LOCAL_IP = "127.0.0.1";
-
//服务器IP
-
private static String SERVER_IP = null;
-
-
/**
-
* 获取客户单IP地址
-
*/
-
public static String getClientIp(HttpServletRequest request) {
-
String ip = request.getHeader("x-forwarded-for");
-
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.getHeader("HTTP_CLIENT_IP");
-
}
-
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
-
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
-
}
-
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
-
ip = request.getRemoteAddr();
-
}
-
if (StringUtils.equalsIgnoreCase("0:0:0:0:0:0:0:1", ip)) {
-
ip = LOCAL_IP;
-
}
-
return ip;
-
}
-
-
/**
-
* @param ip
-
* @return
-
*/
-
public static boolean noInternet(String ip) {
-
return !isInternet(ip);
-
}
-
-
/**
-
* 判定是否是内网地址
-
*
-
* @param ip
-
* @return
-
*/
-
public static boolean isInternet(String ip) {
-
if (StringUtils.isEmpty(ip)) {
-
return false;
-
}
-
if (StringUtils.equals("0:0:0:0:0:0:0:1", ip)) {
-
return true;
-
}
-
Pattern reg = Pattern.compile("^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$");
-
Matcher match = reg.matcher(ip);
-
return match.find();
-
}
-
-
/**
-
* 获取服务器端的IP
-
*/
-
public static String getServerIp() {
-
if (StringUtils.isNotEmpty(SERVER_IP)) {
-
return SERVER_IP;
-
}
-
try {
-
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
-
while (allNetInterfaces.hasMoreElements()) {
-
NetworkInterface netInterface = allNetInterfaces.nextElement();
-
String name = netInterface.getName();
-
if (!StringUtils.contains(name, "docker") && !StringUtils.contains(name, "lo")) {
-
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
-
while (addresses.hasMoreElements()) {
-
InetAddress ip = addresses.nextElement();
-
//loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
-
if (ip != null
-
&& !ip.isLoopbackAddress()
-
&& !ip.getHostAddress().contains(":")) {
-
SERVER_IP = ip.getHostAddress();
-
break;
-
}
-
}
-
}
-
}
-
} catch (Exception e) {
-
SERVER_IP = LOCAL_IP;
-
}
-
return SERVER_IP;
-
}
文章来源: baocl.blog.csdn.net,作者:小黄鸡1992,版权归原作者所有,如需转载,请联系作者。
原文链接:baocl.blog.csdn.net/article/details/113336607
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)