windows和Mac下获取本机IP的方法
public static String getIpAddress() {
String host = "localhost";
//mac系统
if (SystemUtils.IS_OS_MAC_OSX) {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
host = ip.getHostAddress();
return host;
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
//Windows系统
} else {
try (DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
host = socket.getLocalAddress().getHostAddress();
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
return host;
}