参考了https://www.cnblogs.com/starcrm/p/7071227.html
取的局域网内地址,并过滤掉了可能会出现的virbr0地址(192.168.122.1)
代码如下
private static String getLocalIp() throws SocketException {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ip = (InetAddress) addresses.nextElement();
if (ip != null && ip.isSiteLocalAddress() && ip instanceof Inet4Address) {
String ipAddress = ip.getHostAddress();
if ("192.168.122.1".equals(ipAddress)) {
continue;
}
return ipAddress;
}
}
}
return "127.0.0.1";
}
我已经在centos7和windows虚拟机测试过了,符合预期。
欢迎大佬指出漏洞