Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInetAddresses.

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:nfinity.FindPeer.java

public String ScanNetwork() {
    try {//  w w w . j  a  v a 2s .co m
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                if (!inetAddress.getClass().toString().equals("class java.net.Inet6Address")) {
                    if (!inetAddress.isLoopbackAddress()) {
                        try {
                            SubnetUtils utils = new SubnetUtils(inetAddress.getHostAddress() + "/"
                                    + netint.getInterfaceAddresses().get(1).getNetworkPrefixLength());
                            String[] allIps = utils.getInfo().getAllAddresses();
                            return ConnectIP(allIps, inetAddress);
                        } catch (IllegalArgumentException ex) {
                            int prefix = NetworkInterface.getByInetAddress(inetAddress).getInterfaceAddresses()
                                    .get(0).getNetworkPrefixLength();
                            if (!inetAddress.isLoopbackAddress()) {
                                System.out
                                        .println("IP: " + inetAddress.getHostAddress() + " Prefix: " + prefix);
                                SubnetUtils utils = new SubnetUtils(
                                        inetAddress.getHostAddress() + "/" + prefix);
                                String[] allIps = utils.getInfo().getAllAddresses();
                                return ConnectIP(allIps, inetAddress);
                            }
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
        System.out.println("Connection failed " + ex.getMessage());
    }
    return "Peer not found";
}

From source file:com.aurel.track.prop.ApplicationBean.java

/**
 * Retrieve all non-loopback IP addresses from all network interfaces
 *
 * @return the array of assigned IP numbers
 *//*from  w  w  w.  j  av  a  2 s .  c om*/
public static InetAddress[] getInetAddress() {
    List<InetAddress> allIPs = new ArrayList<InetAddress>();
    InetAddress[] allAds = null;

    try {
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it
                        // immediately...
                        allIPs.add(inetAddr);
                        continue;
                    } else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily
                        // site-local.
                        // Store it as a candidate to be returned if
                        // site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback
                        // non-site-local addresses as candidates,
                        // only the first. For subsequent iterations,
                        // candidate will be non-null.
                    }
                }
            }
        }

        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost()
        // returns...
        if (allIPs.isEmpty()) {
            allIPs.add(InetAddress.getLocalHost());
        }

        allAds = new InetAddress[allIPs.size()];
        allAds = allIPs.toArray(allAds);

    } catch (Exception uhn) {
        LOGGER.error(
                "An exception occurred trying to get " + "all IP addresses for this host: " + uhn.getMessage());
    }
    return allAds;
}

From source file:org.apache.hadoop.hbase.regionserver.TestRegionServerHostname.java

@Test(timeout = 120000)
public void testRegionServerHostname() throws Exception {
    final int NUM_MASTERS = 1;
    final int NUM_RS = 1;
    Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();

    while (netInterfaceList.hasMoreElements()) {
        NetworkInterface ni = netInterfaceList.nextElement();
        Enumeration<InetAddress> addrList = ni.getInetAddresses();
        // iterate through host addresses and use each as hostname
        while (addrList.hasMoreElements()) {
            InetAddress addr = addrList.nextElement();
            if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) {
                continue;
            }/*from  w w w . j  ava  2s  .  c  o  m*/
            String hostName = addr.getHostName();
            LOG.info("Found " + hostName + " on " + ni);

            TEST_UTIL.getConfiguration().set(HRegionServer.MASTER_HOSTNAME_KEY, hostName);
            TEST_UTIL.getConfiguration().set(HRegionServer.RS_HOSTNAME_KEY, hostName);
            TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS);
            try {
                ZooKeeperWatcher zkw = TEST_UTIL.getZooKeeperWatcher();
                List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.rsZNode);
                // there would be NUM_RS+1 children - one for the master
                assertTrue(servers.size() == NUM_RS + 1);
                for (String server : servers) {
                    assertTrue("From zookeeper: " + server + " hostname: " + hostName,
                            server.startsWith(hostName.toLowerCase() + ","));
                }
                zkw.close();
            } finally {
                TEST_UTIL.shutdownMiniCluster();
            }
        }
    }
}

From source file:org.apache.carbondata.core.dictionary.service.AbstractDictionaryServer.java

public String findLocalIpAddress(Logger LOGGER) {
    try {//  ww w.j  a  v a 2  s . c  o m
        String defaultIpOverride = System.getenv("SPARK_LOCAL_IP");
        if (defaultIpOverride != null) {
            return defaultIpOverride;
        } else {
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                // Address resolves to something like 127.0.1.1, which happens on Debian; try to find
                // a better address using the local network interfaces
                // getNetworkInterfaces returns ifs in reverse order compared to ifconfig output order
                // on unix-like system. On windows, it returns in index order.
                // It's more proper to pick ip address following system output order.
                Enumeration<NetworkInterface> activeNetworkIFs = NetworkInterface.getNetworkInterfaces();
                List<NetworkInterface> reOrderedNetworkIFs = new ArrayList<NetworkInterface>();
                while (activeNetworkIFs.hasMoreElements()) {
                    reOrderedNetworkIFs.add(activeNetworkIFs.nextElement());
                }

                if (!SystemUtils.IS_OS_WINDOWS) {
                    Collections.reverse(reOrderedNetworkIFs);
                }

                for (NetworkInterface ni : reOrderedNetworkIFs) {
                    Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress addr = inetAddresses.nextElement();
                        if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                                && addr instanceof Inet4Address) {
                            // We've found an address that looks reasonable!
                            LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                                    + " resolves to a loopback address: " + address.getHostAddress()
                                    + "; using " + addr.getHostAddress() + " instead (on interface "
                                    + ni.getName() + ")");
                            LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                            return addr.getHostAddress();
                        }
                    }
                    LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                            + " resolves to a loopback address: " + address.getHostAddress()
                            + ", but we couldn't find any external IP address!");
                    LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                }
            }
            return address.getHostAddress();
        }
    } catch (UnknownHostException e) {
        LOGGER.error("do not get local host address:" + e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (SocketException e) {
        LOGGER.error("do not get net work interface:" + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.github.tomakehurst.wiremock.BindAddressTest.java

private String getIpAddressOtherThan(String lopbackAddress) throws SocketException {
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInterface : Collections.list(networkInterfaces)) {
        Enumeration<InetAddress> inetAddresses = netInterface.getInetAddresses();
        for (InetAddress address : Collections.list(inetAddresses)) {
            if (address instanceof Inet4Address && !address.getHostAddress().equals(lopbackAddress)) {
                return address.getHostAddress();
            }//from   w w  w.  j  a  v a  2s.  c o  m
        }
    }
    return null;
}

From source file:com.motelabs.chromemote.bridge.MainActivity.java

private String getLocalIpAddress() {
    try {/*from  w  ww.  ja va 2  s  .c  om*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    String ipAddr = inetAddress.getHostAddress();
                    return ipAddr;
                }
            }
        }
    } catch (SocketException ex) {
        //Log.d(TAG, ex.toString());
    }
    return null;
}

From source file:com.smartdevicelink.tcpdiscovery.DiscoveredDevice.java

private String getLocalAddressForIface(String ifaceName) throws Exception {
    NetworkInterface iface = NetworkInterface.getByName(ifaceName);
    Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
        if (InetAddressUtils.isIPv4Address(inetAddress.toString())) {
            return inetAddress.toString();
        }/*from  w  ww.  j  a  v a  2 s . c  om*/
    }
    return "";
}

From source file:org.sonar.server.platform.ServerIdGenerator.java

public List<InetAddress> getAvailableAddresses() {
    List<InetAddress> result = Lists.newArrayList();
    try {/*from  w  w  w . j a va  2s.  c  o m*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ownedAddress = addresses.nextElement();
                if (isFixed(ownedAddress)) {
                    result.add(ownedAddress);
                }
            }
        }
    } catch (SocketException e) {
        LoggerFactory.getLogger(ServerIdGenerator.class).error("Fail to browse network interfaces", e);
    }
    return result;
}

From source file:ru.asmsoft.p2p.incoming.LocalAddressesFilteringService.java

@PostConstruct
public void init() {
    try {//from  ww w  . ja va 2  s. c o  m
        logger.info("Full list of Network Interfaces:");
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            logger.info("    " + intf.getName() + " " + intf.getDisplayName());
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                String ip = enumIpAddr.nextElement().toString().replace("/", "");
                logger.info("        " + ip);
                localIpAddresses.add(ip);
            }
        }
    } catch (SocketException e) {
        logger.info(" (error retrieving network interface list)");
    }
}

From source file:terrastore.communication.NodeConfiguration.java

private String getPublishAddresses() throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
    StringBuilder result = new StringBuilder();
    while (nics != null && nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        if (nic.isUp() && !nic.isLoopback() && !nic.isVirtual() && nic.getInetAddresses().hasMoreElements()) {
            Enumeration<InetAddress> addresses = nic.getInetAddresses();
            while (addresses.hasMoreElements()) {
                if (result.length() > 0) {
                    result.append(",");
                }/*from www  .  j  a  v  a2  s.  c o m*/
                result.append(addresses.nextElement().getHostAddress());
            }
        }
    }
    return result.toString();
}