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;
}
}