1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.omid;
19
20 import java.net.DatagramSocket;
21 import java.net.InetAddress;
22 import java.net.NetworkInterface;
23 import java.net.SocketException;
24 import java.util.Collections;
25 import java.util.Enumeration;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public class NetworkUtils {
31
32 private static final Logger LOG = LoggerFactory.getLogger(NetworkUtils.class);
33
34 private static final String LINUX_TSO_NET_IFACE_PREFIX = "eth";
35 private static final String MAC_TSO_NET_IFACE_PREFIX = "en";
36
37 public static String getDefaultNetworkInterface() {
38
39 try (DatagramSocket s=new DatagramSocket()) {
40 s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0);
41 return NetworkInterface.getByInetAddress(s.getLocalAddress()).getName();
42 } catch (Exception e) {
43
44 }
45
46
47 try {
48 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
49 String fallBackName = null;
50 while (networkInterfaces.hasMoreElements()) {
51 NetworkInterface nextElement = networkInterfaces.nextElement();
52 String name = nextElement.getDisplayName();
53 LOG.info("Iterating over network interfaces, found '{}'", name);
54 boolean hasInet = Collections.list(nextElement.getInetAddresses()).size() > 1;
55 if (hasInet && fallBackName == null) {
56 fallBackName = name;
57 }
58 if ((name.startsWith(MAC_TSO_NET_IFACE_PREFIX) && hasInet ) ||
59 name.startsWith(LINUX_TSO_NET_IFACE_PREFIX)) {
60 return name;
61 }
62 }
63 if (fallBackName != null) {
64 return fallBackName;
65 }
66 } catch (SocketException ignored) {
67 throw new RuntimeException("Failed to find any network interfaces", ignored);
68 }
69
70 throw new IllegalArgumentException(String.format("No network '%s*'/'%s*' interfaces found",
71 MAC_TSO_NET_IFACE_PREFIX, LINUX_TSO_NET_IFACE_PREFIX));
72 }
73 }