Skip to content

Instantly share code, notes, and snippets.

@EvanYellow
Created December 9, 2013 12:08
Show Gist options
  • Save EvanYellow/7871318 to your computer and use it in GitHub Desktop.
Save EvanYellow/7871318 to your computer and use it in GitHub Desktop.
es select intf
/**
* Returns the first non-loopback address on any interface on the current host.
*
* @param ip_version Constraint on IP version of address to be returned, 4 or 6
*/
public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throws SocketException {
InetAddress address = null;
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
List<NetworkInterface> intfsList = Lists.newArrayList();
while (intfs.hasMoreElements()) {
intfsList.add((NetworkInterface) intfs.nextElement());
}
// order by index, assuming first ones are more interesting
try {
final Method getIndexMethod = NetworkInterface.class.getDeclaredMethod("getIndex");
getIndexMethod.setAccessible(true);
CollectionUtil.timSort(intfsList, new Comparator<NetworkInterface>() {
@Override
public int compare(NetworkInterface o1, NetworkInterface o2) {
try {
return ((Integer) getIndexMethod.invoke(o1)).intValue() - ((Integer) getIndexMethod.invoke(o2)).intValue();
} catch (Exception e) {
throw new ElasticSearchIllegalStateException("failed to fetch index of network interface");
}
}
});
} catch (Exception e) {
// ignore
}
for (NetworkInterface intf : intfsList) {
try {
if (!intf.isUp() || intf.isLoopback())
continue;
} catch (Exception e) {
// might happen when calling on a network interface that does not exists
continue;
}
address = getFirstNonLoopbackAddress(intf, ip_version);
if (address != null) {
return address;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment