如何获取默认网络适配器的主机广播地址? Java

How do you get host's broadcast address of the default network adapter? Java

如何获取 Java 中默认网络适配器的主机广播地址?

试试这个:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) 
{
    NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback())
        continue;    // Do not want to use the loopback interface.
    for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) 
    {
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast == null)
            continue;

        // Do something with the address.
    }
}

与预期答案相同的想法,但使用 Streams
(没有检查它是否具有性能或任何其他优势)。

所有可用广播地址的流:

public static Stream<InetAddress> getBroadcastAddresses(boolean ignoreLoopBack)
throws SocketException {
    return NetworkInterface.networkInterfaces()
        .filter(n -> !ignoreLoopBack || notLoopBack(n))
        .map(networkInterface ->
            networkInterface.getInterfaceAddresses()
                .stream()
                .map(InterfaceAddress::getBroadcast)
                .filter(Objects::nonNull)
        )
        .flatMap(i -> i); // stream of streams to a single stream
}

一个可选的第一个找到的广播地址(可以为空):

public static Optional<InetAddress> getBroadcastAddress(boolean ignoreLoopBack) 
throws SocketException {
    return NetworkInterface.networkInterfaces()
            .filter(n -> !ignoreLoopBack || notLoopBack(n))
            .map(networkInterface ->
                    networkInterface.getInterfaceAddresses()
                        .stream()
                        .map(InterfaceAddress::getBroadcast)
                        .filter(Objects::nonNull)
                        .findFirst()
            )
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst();
}

避免在流上执行的 lambda 中出现异常的辅助方法:

private static boolean notLoopBack(NetworkInterface networkInterface) {
    try {
        return !networkInterface.isLoopback();
    } catch (SocketException e) {
        // should not happen, but if it does: throw RuntimeException
        throw new RuntimeException(e);
    }
}