CodeCamper
CodeCamper

Reputation: 6980

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

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

Upvotes: 2

Views: 4117

Answers (2)

Amir Kirsh
Amir Kirsh

Reputation: 13752

The same idea as the expected answer but with Streams.
(Didn't check if it has a performance or any other advantage).

A Stream of all available broadcast addresses:

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
}

An Optional of the first found broadcast address (can be empty):

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 method to avoid exception inside a lambda performing on a stream:

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);
    }
}

Upvotes: 0

Dermot Blair
Dermot Blair

Reputation: 1620

Try this:

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

Upvotes: 5

Related Questions