windows
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
linux and windows
获取第一个非环回ip
String hostAddress = null;
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getName().equals("lo")) {
continue;
}
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress != null && inetAddress instanceof Inet4Address) {
hostAddress = inetAddress.getHostAddress();
break;
}
}
if (hostAddress != null) {
break;
}
}
本文介绍了一种在Windows和Linux平台上获取非环回IP地址的方法。通过遍历网络接口并检查每个接口上的IPv4地址来实现。该方法跳过环回接口确保获取的是有效的外部IP地址。
322





