Skip to content

TcpUtils.java only uses the first found non-local host address  #89

@dmsquires

Description

@dmsquires

When playing with multiple network gateways this becomes a problem with registering incorrect IP's in zookeeper. (eg can become non-trivial when using multiple gateways with Docker). The default behavior on CentOS with eth0 and docker0 in this case to pick up the docker0 gateway, which may not be what is desired.

public class TcpUtils {

    public static InetAddress getFirstNonLocalhostInetAddress() throws SocketException {
        final List<InetAddress> addrs = getAllInetAddress();
        return addrs.stream()
                .filter(i -> !i.isLoopbackAddress() && i instanceof Inet4Address)
                .findFirst()
                .orElseThrow(() -> new DempsyException("There are no non-local network interfaces among " + addrs));
    }

    public static List<InetAddress> getAllInetAddress() throws SocketException {
        final List<InetAddress> ret = new ArrayList<>();
        final Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = netInterfaces.nextElement();
            for (final Enumeration<InetAddress> loopInetAddress = networkInterface.getInetAddresses(); loopInetAddress.hasMoreElements();) {
                final InetAddress tempInetAddress = loopInetAddress.nextElement();
                ret.add(tempInetAddress);
            }
        }
        return ret;
    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions