在项目中有很多关于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;
/**
* 获取客户单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;
}