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

时间:2015-03-24 17:01:05

标签: java networking

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

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

与预期答案相同的想法,但具有 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();
}

Helper方法,以避免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);
    }
}