Skip to content

Commit 3a52c2f

Browse files
committed
Improve automatic publish network address logic, closes elastic#439.
1 parent bad45de commit 3a52c2f

File tree

1 file changed

+28
-1
lines changed
  • modules/elasticsearch/src/main/java/org/elasticsearch/common/network

1 file changed

+28
-1
lines changed

modules/elasticsearch/src/main/java/org/elasticsearch/common/network/NetworkUtils.java

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,13 @@
1919

2020
package org.elasticsearch.common.network;
2121

22+
import org.elasticsearch.ElasticSearchIllegalStateException;
23+
import org.elasticsearch.common.collect.Lists;
2224
import org.elasticsearch.common.logging.ESLogger;
2325
import org.elasticsearch.common.logging.Loggers;
2426
import org.elasticsearch.common.os.OsUtils;
2527

28+
import java.lang.reflect.Method;
2629
import java.net.*;
2730
import java.util.*;
2831

@@ -95,15 +98,39 @@ public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throw
9598
InetAddress address = null;
9699

97100
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
101+
102+
List<NetworkInterface> intfsList = Lists.newArrayList();
98103
while (intfs.hasMoreElements()) {
99-
NetworkInterface intf = (NetworkInterface) intfs.nextElement();
104+
intfsList.add((NetworkInterface) intfs.nextElement());
105+
}
106+
107+
// order by index, assuming first ones are more interesting
108+
try {
109+
final Method getIndexMethod = NetworkInterface.class.getDeclaredMethod("getIndex");
110+
getIndexMethod.setAccessible(true);
111+
112+
Collections.sort(intfsList, new Comparator<NetworkInterface>() {
113+
@Override public int compare(NetworkInterface o1, NetworkInterface o2) {
114+
try {
115+
return ((Integer) getIndexMethod.invoke(o1)).intValue() - ((Integer) getIndexMethod.invoke(o2)).intValue();
116+
} catch (Exception e) {
117+
throw new ElasticSearchIllegalStateException("failed to fetch index of network interface");
118+
}
119+
}
120+
});
121+
} catch (Exception e) {
122+
// ignore
123+
}
124+
125+
for (NetworkInterface intf : intfsList) {
100126
if (!intf.isUp() || intf.isLoopback())
101127
continue;
102128
address = getFirstNonLoopbackAddress(intf, ip_version);
103129
if (address != null) {
104130
return address;
105131
}
106132
}
133+
107134
return null;
108135
}
109136

0 commit comments

Comments
 (0)