java獲取本機IP (相容linux)
阿新 • • 發佈:2019-02-16
程式在本地沒問題,釋出到linux上報錯,百度了一下是ip獲取方法InetAddress.getLocalHost().getHostAddress()不相容linux,網上提供一種解決方案是修改linux伺服器配置,我試了一下,沒用,於是採用另一種方案,如下:
private static 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) {
System.out.println("獲取ip地址異常" );
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
public static String getLocalIP() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLinuxLocalIp();
}
}