|
19 | 19 |
|
20 | 20 | package org.elasticsearch.common.network;
|
21 | 21 |
|
| 22 | +import org.elasticsearch.ElasticSearchIllegalStateException; |
| 23 | +import org.elasticsearch.common.collect.Lists; |
22 | 24 | import org.elasticsearch.common.logging.ESLogger;
|
23 | 25 | import org.elasticsearch.common.logging.Loggers;
|
24 | 26 | import org.elasticsearch.common.os.OsUtils;
|
25 | 27 |
|
| 28 | +import java.lang.reflect.Method; |
26 | 29 | import java.net.*;
|
27 | 30 | import java.util.*;
|
28 | 31 |
|
@@ -95,15 +98,39 @@ public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throw
|
95 | 98 | InetAddress address = null;
|
96 | 99 |
|
97 | 100 | Enumeration intfs = NetworkInterface.getNetworkInterfaces();
|
| 101 | + |
| 102 | + List<NetworkInterface> intfsList = Lists.newArrayList(); |
98 | 103 | 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) { |
100 | 126 | if (!intf.isUp() || intf.isLoopback())
|
101 | 127 | continue;
|
102 | 128 | address = getFirstNonLoopbackAddress(intf, ip_version);
|
103 | 129 | if (address != null) {
|
104 | 130 | return address;
|
105 | 131 | }
|
106 | 132 | }
|
| 133 | + |
107 | 134 | return null;
|
108 | 135 | }
|
109 | 136 |
|
|
0 commit comments