獲取windows和linux獲取本機ip
阿新 • • 發佈:2020-06-20
InetAddress.getLocalHost().getHostAddress()
獲取本機ip在linux上報錯: Caused by: java.net.UnknownHostException
資訊如下
Caused by: java.net.UnknownHostException: host-xxx: Name or service not known at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1324) at java.net.InetAddress.getLocalHost(InetAddress.java:1501) ... 76 common frames omitted
原因:上邊的程式碼只能在windows獲取ip,在linux上不行(linux解決方案也行,但是一般開發沒運維那麼大的許可權啊!!!)
java程式碼解決方案:
package cxshyf.msjt.sign.utils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; /** * 常用工具類 */ public class IPUtils { /** * 獲取本地IP地址 * * @throws SocketException */ public static String getLocalIP() throws UnknownHostException { if (isWindowsOS()) { return InetAddress.getLocalHost().getHostAddress(); } else { return getLinuxLocalIp(); } } /** * 判斷作業系統是否是Windows * * @return */ public static 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 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(); if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) { ip = ipaddress; System.out.println(ipaddress); } } } } } } catch (SocketException ex) { System.out.println("獲取ip地址異常"); ip = "127.0.0.1"; ex.printStackTrace(); } return ip; } }
參考: