獲取本地IP工具類
阿新 • • 發佈:2019-01-06
方式一:InetAddress工具類
public static String getLocalIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
存在問題: 如果在虛擬機器或Docker容器上執行可能返回127.0.0.1;
方式二:使用網絡卡地址
/** * 直接根據第一個網絡卡地址作為其內網ipv4地址,避免返回 127.0.0.1 * * @return */ public static String getLocalIpByNetcard() { try { for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) { NetworkInterface item = e.nextElement(); for (InterfaceAddress address : item.getInterfaceAddresses()) { if (item.isLoopback() || !item.isUp()) { continue; } if (address.getAddress() instanceof Inet4Address) { Inet4Address inet4Address = (Inet4Address) address.getAddress(); return inet4Address.getHostAddress(); } } } return InetAddress.getLocalHost().getHostAddress(); } catch (SocketException | UnknownHostException e) { throw new RuntimeException(e); } }
參考: