/**
* 获取ip
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public String getServerIp() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return getWindowIp();
} else {
return getLinuxLocalIp();
}
}
/**
* 获取window服务器ip
* @return
*/
public static String getWindowIp(){
String SERVER_IP = null;
try {
InetAddress address = InetAddress.getLocalHost();
SERVER_IP = address.getHostAddress();//获取IP地址
} catch (Exception e) {
e.printStackTrace();
}
return SERVER_IP;
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取Linux下的IP地址
*
* @return IP地址
* @throws SocketException
*/
private String getLinuxLocalIp() throws SocketException {
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) {
log.error("获取ip地址异常", ex);
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
区分window和linux获取服务器ip
最新推荐文章于 2024-02-06 10:21:22 发布