IP工具类
public class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
private static final String REG_EXP_IP = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
private static final String CMD_GET_HOST_IP = "ifconfig {0} | grep \"inet addr\" | awk ''$1==\"inet\" '{print $2'}'' | awk -F: '''{print $2'}''";
private static final String CMD_GET_HOST_IP_OS7 = "ifconfig {0} | grep \"inet\" | awk ''$1==\"inet\" '{print $2'}''";
private static final String CONFIG_DEFAULT_NETWORK = "/etc/network/default_gw";
public IPUtils() {
}
public static String getHostName() {
String hostName = System.getenv("COMPUTERNAME");
if (!StringUtils.isEmpty(hostName)) {
return hostName;
} else {
try {
InetAddress inetAddress = Inet4Address.getLocalHost();
if (inetAddress != null) {
hostName = inetAddress.getHostName();
}
} catch (UnknownHostException var4) {
String host = var4.getMessage();
if (!StringUtils.isEmpty(host)) {
int colon = host.indexOf(":");
if (colon > 0) {
hostName = host.substring(0, colon);
}
}
}
return hostName;
}
}
public static String getHostIp(String networkName) {
String hostIp = "";
if (OSCategory.WINDOWS.equals(OSCategory.currentOS())) {
try {
hostIp = InetAddress.getLocalHost().getHostAddress();
if (logger.isDebugEnabled()) {
logger.debug("get host ip (windows) success: {}", hostIp);
}
} catch (UnknownHostException var3) {
logger.error("get host ip (windows) failed", var3);
}
} else if (StringUtils.isEmpty(networkName)) {
hostIp = getHostIp();
} else {
hostIp = getLinuxHostIpByCmd(networkName);
}
if (StringUtils.isEmpty(hostIp)) {
logger.error("get host ip failure, maybe invalid network name or bad configuration");
}
return hostIp;
}
private static String getLinuxHostIpByCmd(String networkName) {
String localIP = "";
if (StringUtils.isEmpty(networkName)) {
networkName = "eth0";
}
String getIpCmd = "";
try {
getIpCmd = MessageFormat.format("ifconfig {0} | grep \"inet\" | awk ''$1==\"inet\" '{print $2'}''", networkName);
localIP = ShellUtils.execLinuxCmd(getIpCmd);
String pattern = "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(localIP);
if (m.find()) {
localIP = m.group(0);
}
if (logger.isDebugEnabled()) {
logger.debug("get host ip (linux-{}, by cmd) success: {}", networkName, localIP);
}
} catch (Throwable var6) {
logger.debug("get host ip by cmd failed, getIpCmd: {}, exception: {}", getIpCmd, var6);
}
return localIP;
}
public static String getHostIp() {
String localIP = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
label47:
while(true) {
NetworkInterface networkInterface;
do {
do {
do {
if (!interfaces.hasMoreElements()) {
break label47;
}
networkInterface = (NetworkInterface)interfaces.nextElement();
} while(networkInterface.isLoopback());
} while(networkInterface.isVirtual());
} while(!networkInterface.isUp());
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress address = (InetAddress)addresses.nextElement();
localIP = address.getHostAddress();
Matcher matcher = Pattern.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}").matcher(localIP);
if (matcher.matches()) {
break label47;
}
}
}
} catch (SocketException var6) {
logger.error("get host ip (linux, by NetworkInterface) failed, exception: {}", var6);
}
if (logger.isDebugEnabled()) {
logger.debug("get host ip (linux, by NetworkInterface) success: {}", localIP);
}
return localIP;
}
public static String getHostIpByConfig() {
String result = null;
try {
if (FileUtil.exist("/etc/network/default_gw")) {
String text = FileUtil.readString("/etc/network/default_gw", "UTF-8");
if (StringUtils.isEmpty(text)) {
return "";
}
String[] strs = text.split("=");
if (strs != null && strs.length > 1) {
String networkName = strs[1].trim();
result = getLinuxHostIpByCmd(networkName);
}
}
} catch (Exception var4) {
logger.error("getHostIpByConfig failed, exception: {}", var4);
}
return result;
}
public static List<String> getAvailableHostIpList() {
List<String> ipList = new ArrayList();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
label47:
while(true) {
NetworkInterface networkInterface;
do {
do {
do {
if (!interfaces.hasMoreElements()) {
break label47;
}
networkInterface = (NetworkInterface)interfaces.nextElement();
} while(networkInterface.isLoopback());
} while(networkInterface.isVirtual());
} while(!networkInterface.isUp());
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress address = (InetAddress)addresses.nextElement();
String ipString = address.getHostAddress();
Matcher matcher = Pattern.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}").matcher(ipString);
if (matcher.matches()) {
ipList.add(ipString);
}
}
}
} catch (SocketException var7) {
logger.error("get host ip (linux, by NetworkInterface) failed, exception: {}", var7);
}
if (logger.isDebugEnabled()) {
logger.debug("get host ip (linux, by NetworkInterface) success: {}", JSON.toJSONString(ipList));
}
return ipList;
}
public static String getHostMac(String ip) {
String macAddress = "";
try {
if (StringUtils.isEmpty(ip) || "127.0.0.1".equals(ip)) {
ip = getHostIp();
}
if (StringUtils.isEmpty(ip)) {
return "";
}
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(InetAddress.getByName(ip));
if (networkInterface == null) {
return "";
}
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuffer macBuffer = new StringBuffer("");
for(int i = 0; i < macBytes.length; ++i) {
if (i > 0) {
macBuffer.append("-");
}
int temp = macBytes[i] & 255;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
macBuffer.append("0" + str);
} else {
macBuffer.append(str);
}
}
macAddress = macBuffer.toString().toUpperCase();
} catch (UnknownHostException | SocketException var8) {
logger.error("get host mac (linux, by NetworkInterface) failed, exception: {}", var8);
}
if (logger.isDebugEnabled()) {
}
return macAddress;
}
public static String getRemoteHost(HttpServletRequest request) {
String ip = request.getHeader("x-real-ip");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
if (logger.isDebugEnabled()) {
logger.debug("get client ip from header X-Real-IP is: {}", ip);
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
if (ip != null && ip.length() != 0 && ip.indexOf(",") != -1) {
ip = ip.split(",")[0];
}
}
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();
}
return ip;
}
public static boolean isReachable(String ip) {
boolean flag = false;
try {
InetAddress address = InetAddress.getByName(ip);
flag = address.isReachable(3000);
if (logger.isDebugEnabled()) {
logger.debug("addr :" + ip + ", isReachable:" + flag);
}
} catch (Exception var3) {
logger.debug("Unknown host " + ip);
}
return flag;
}
public static boolean isReachable(String ip, String port) {
boolean flag = false;
Socket socket = null;
try {
socket = new Socket(ip, Integer.parseInt(port));
if (logger.isDebugEnabled()) {
logger.debug("addr :" + ip + ", isReachable:" + flag);
}
flag = true;
} catch (Exception var13) {
logger.debug("Unknown host : " + ip + ":" + port);
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException var12) {
logger.error(var12.getMessage(), var12);
}
}
return flag;
}
public static String toIpNumberStr(String ip) {
String result = null;
if (!StringUtils.isEmpty(ip)) {
StringBuilder ipNumStrBuilder = new StringBuilder();
String[] ipSegments = ip.split("\\.");
Format decimalFormat = new DecimalFormat("000");
try {
String[] var5 = ipSegments;
int var6 = ipSegments.length;
for(int var7 = 0; var7 < var6; ++var7) {
String ipSeg = var5[var7];
Integer ipSegInt = Integer.valueOf(ipSeg);
ipNumStrBuilder.append(decimalFormat.format(ipSegInt));
}
} catch (Exception var10) {
}
result = ipNumStrBuilder.toString();
}
return result;
}
public static long convert2Long(String ip) {
long result = 0L;
Matcher matcher = Pattern.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}").matcher(ip);
if (matcher.matches()) {
String[] ipSegments = ip.split("\\.");
for(int i = 0; i < ipSegments.length; ++i) {
long segValue = Long.parseLong(ipSegments[i]);
result = (long)((double)result + (double)segValue * Math.pow(256.0, (double)i));
}
}
return result;
}
public static String convert2Ip(long value) {
StringBuilder result = new StringBuilder(15);
for(int i = 0; i < 4; ++i) {
result.append(Long.toString(value & 255L));
if (i < 3) {
result.append(".");
}
value >>= 8;
}
return result.toString();
}
public static String convert2Hex(String ip, boolean isLowerCase, Integer fixedLength) {
String hexResultString = "";
fixedLength = fixedLength == null ? 8 : fixedLength;
long longValue = convert2Long(ip);
String hexString = Long.toHexString(longValue);
if (!StringUtils.isEmpty(hexString) && hexString.length() < fixedLength) {
while(hexString.length() < 8) {
hexString = "0" + hexString;
}
}
if (isLowerCase) {
hexResultString = hexString.toLowerCase();
} else {
hexResultString = hexString.toUpperCase();
}
return hexResultString;
}
public static String convert2Ip(String stringHex) {
String regex = "^[A-Fa-f0-9]{1,8}$";
if (!stringHex.matches(regex)) {
return "";
} else {
long value = Long.parseLong(stringHex, 16);
return convert2Ip(value);
}
}
public static String getLinuxLocalIp() {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
}