我使用的是简单的InetAddress.getLocalHost().getHostAddress(),但对于其中一台服务器,它提供了127.0.0.0 ip地址,这不是预期的ip地址。为了从服务器获得实际的ip地址,我现在使用下面的代码,但想让它更简单。我们可以将下面的代码简化为java 8的流代码吗?
public static InetAddress getInetAddress() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
return ia;
}
}
}
return null;
}发布于 2020-10-23 03:42:59
可以使用Collections.list将枚举转换为ArrayList,然后使用List's stream和相关Stream API函数筛选出不必要的InetAddress实例,并选择符合条件的第一个实例:
public static InetAddress getInetAddress() throws SocketException {
return Collections
.list(NetworkInterface.getNetworkInterfaces())
.stream() // Stream<NetworkInterface>
.flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) // Stream<InetAddress>
.filter(ia -> !ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address)
.findFirst() // Optional<InetAddress>
.orElse(null);
}https://stackoverflow.com/questions/64487915
复制相似问题