diff --git a/src/main/java/org/elasticsearch/common/network/NetworkService.java b/src/main/java/org/elasticsearch/common/network/NetworkService.java index f07a5256a88..1a4391d6bce 100644 --- a/src/main/java/org/elasticsearch/common/network/NetworkService.java +++ b/src/main/java/org/elasticsearch/common/network/NetworkService.java @@ -172,11 +172,15 @@ public class NetworkService extends AbstractComponent { } Collection allInterfs = NetworkUtils.getAllAvailableInterfaces(); for (NetworkInterface ni : allInterfs) { - if (!ni.isUp() || ni.isLoopback()) { + if (!ni.isUp()) { continue; } if (host.equals(ni.getName()) || host.equals(ni.getDisplayName())) { - return NetworkUtils.getFirstNonLoopbackAddress(ni, stackType); + if (ni.isLoopback()) { + return NetworkUtils.getFirstAddress(ni, stackType); + } else { + return NetworkUtils.getFirstNonLoopbackAddress(ni, stackType); + } } } } diff --git a/src/main/java/org/elasticsearch/common/network/NetworkUtils.java b/src/main/java/org/elasticsearch/common/network/NetworkUtils.java index d94ce50172e..ad95e09bb19 100644 --- a/src/main/java/org/elasticsearch/common/network/NetworkUtils.java +++ b/src/main/java/org/elasticsearch/common/network/NetworkUtils.java @@ -162,6 +162,25 @@ public abstract class NetworkUtils { return null; } + /** + * Returns the first address with the proper ipVersion on the given interface on the current host. + * + * @param intf the interface to be checked + * @param ipVersion Constraint on IP version of address to be returned, 4 or 6 + */ + public static InetAddress getFirstAddress(NetworkInterface intf, StackType ipVersion) throws SocketException { + if (intf == null) + throw new IllegalArgumentException("Network interface pointer is null"); + + for (Enumeration addresses = intf.getInetAddresses(); addresses.hasMoreElements(); ) { + InetAddress address = (InetAddress) addresses.nextElement(); + if ((address instanceof Inet4Address && ipVersion == StackType.IPv4) || + (address instanceof Inet6Address && ipVersion == StackType.IPv6)) + return address; + } + return null; + } + /** * A function to check if an interface supports an IP version (i.e has addresses * defined for that IP version).