NetUtils { public static int findHostIndex(String[] hosts) throws UnknownHostException, SocketException { InetAddress[][] hostAddrsLst = new InetAddress[hosts.length][]; for (int i = 0; i < hosts.length; i++) { InetAddress[] hostAddrs = InetAddress.getAllByName(hosts[i]); hostAddrsLst[i] = InetAddress.getAllByName(hosts[i]); for (InetAddress hostAddr : hostAddrs) { if (hostAddr.isLoopbackAddress()) { return i; } } } Enumeration<NetworkInterface> nics = NetworkInterface .getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> iaddrs = nic.getInetAddresses(); while (iaddrs.hasMoreElements()) { InetAddress laddr = iaddrs.nextElement(); for (int i = 0; i < hosts.length; i++) { List<InetAddress> maddrs = Arrays.asList(hostAddrsLst[i]); if (maddrs.contains(laddr)) { return i; } } } } return -1; }  static String localhost(); static void setLocalhost(String host); static Pair<String, Integer> parseHostPortPair(String sock,
      int portDefault); static int findHostIndex(String[] hosts); static final Logger LOG; }
@Test public void testIsLocalHost() throws UnknownHostException, SocketException { assertEquals(0, NetUtils.findHostIndex(new String[] { "127.0.0.1" })); assertEquals(0, NetUtils.findHostIndex(new String[] { "localhost" })); assertEquals(0, NetUtils.findHostIndex(new String[] { "127.1.0.1" })); }
@Test public void testIsLocalHostIdx() throws UnknownHostException, SocketException { assertEquals(1, NetUtils.findHostIndex(new String[] { "google.com", "127.0.0.1" })); assertEquals(2, NetUtils.findHostIndex(new String[] { "microsoft.com", "twitter.com", "localhost" })); assertEquals(0, NetUtils.findHostIndex(new String[] { "127.1.0.1", "cloudera.com", "yahoo.com" })); assertEquals(-1, NetUtils.findHostIndex(new String[] { "apache.org", "cloudera.com", "yahoo.com" })); }
@Test(expected = UnknownHostException.class) public void testBadHost() throws UnknownHostException, SocketException { NetUtils.findHostIndex(new String[] { "baddnsname" }); }