Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:org.apache.htrace.core.TracerId.java

/**
 * <p>Get the best IP address that represents this node.</p>
 *
 * This is complicated since nodes can have multiple network interfaces,
 * and each network interface can have multiple IP addresses.  What we're
 * looking for here is an IP address that will serve to identify this node
 * to HTrace.  So we prefer site-local addresess (i.e. private ones on the
 * LAN) to publicly routable interfaces.  If there are multiple addresses
 * to choose from, we select the one which comes first in textual sort
 * order.  This should ensure that we at least consistently call each node
 * by a single name.//from ww  w. j  a v a 2s. c  o  m
 */
static String getBestIpString() {
    Enumeration<NetworkInterface> ifaces;
    try {
        ifaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOG.error("Error getting network interfaces", e);
        return "127.0.0.1";
    }
    TreeSet<String> siteLocalCandidates = new TreeSet<String>();
    TreeSet<String> candidates = new TreeSet<String>();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        for (Enumeration<InetAddress> addrs = iface.getInetAddresses(); addrs.hasMoreElements();) {
            InetAddress addr = addrs.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr.isSiteLocalAddress()) {
                    siteLocalCandidates.add(addr.getHostAddress());
                } else {
                    candidates.add(addr.getHostAddress());
                }
            }
        }
    }
    if (!siteLocalCandidates.isEmpty()) {
        return siteLocalCandidates.first();
    }
    if (!candidates.isEmpty()) {
        return candidates.first();
    }
    return "127.0.0.1";
}

From source file:org.springframework.data.hadoop.util.net.DefaultHostInfoDiscovery.java

protected List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
    List<NetworkInterface> interfaces = new ArrayList<NetworkInterface>(5);
    for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
        interfaces.add(e.nextElement());
    }// w w w.  j a v a 2 s  .  c  om
    return interfaces;
}

From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java

/**
 * Send broadcast message over all active interfaces
 *
 * @param discoverString/*from   ww  w  . ja  v  a2 s  .c  o  m*/
 *            String to be used for the discovery
 */
private void sendDiscoveryMessage(String discoverString) {
    DatagramSocket bcSend = null;
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);

        byte[] sendData = discoverString.getBytes();

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = null;

                if (StringUtils.isNotBlank(optionalHost)) {
                    try {
                        broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) };
                    } catch (Exception e) {
                        logger.error("Could not use host for hub discovery", e);
                        return;
                    }
                } else {
                    broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"),
                            InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() };
                }

                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc,
                                    DISCO_PORT);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.debug(e.getMessage(), e);
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(),
                                networkInterface.getDisplayName());
                    }
                }
            }
        }

    } catch (IOException e) {
        logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
    } finally {
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
            // Ignore
        }
    }

}

From source file:eu.musesproject.client.contextmonitoring.sensors.DeviceProtectionSensor.java

public String getIPAddress(boolean useIPv4) {
    try {//ww  w . jav a 2s. c o m
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:org.inaetics.pubsub.demo.config.Configurator.java

private String getIp() {
    try {//from w  ww .  j a v a2  s  .co  m
        Enumeration<NetworkInterface> nEnumeration = NetworkInterface.getNetworkInterfaces();
        while (nEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) nEnumeration.nextElement();
            if (networkInterface.getName().equals("eth1")) {
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) addresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "localhost";
}

From source file:com.offbynull.portmapper.common.NetworkUtils.java

/**
 * Set a {@link MulticastChannel} to listen on all IPv4 interfaces.
 * @param channel multicast channel to listen on
 * @throws IOException if there's an error
 * @throws NullPointerException if any argument is {@code null}
 *///from   w ww . jav  a  2s .  c  o  m
public static void multicastListenOnAllIpv4InterfaceAddresses(MulticastChannel channel) throws IOException {
    Validate.notNull(channel);

    final InetAddress ipv4Group = InetAddress.getByName("224.0.0.1"); // NOPMD

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
        while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
            InetAddress addr = addrs.nextElement();

            try {
                if (addr instanceof Inet4Address) {
                    channel.join(ipv4Group, networkInterface);
                }
            } catch (IOException ioe) { // NOPMD
                // occurs with certain interfaces
                // do nothing
            }
        }
    }
}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Interface method implementation.//from  w ww  .  j a v  a2 s  .com
 * Also sets the hostName
 * @see JobConfigurationService#setPort(int)
 */
@Override
public void setPort(int port) {
    String hostName = "";
    String ipAddr = "";
    try {
        hostName = InetAddress.getLocalHost().getHostName();
        ipAddr = InetAddress.getLocalHost().getHostAddress();
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        //Iterate through all network interfaces
        while (nets.hasMoreElements()) {
            NetworkInterface netint = (NetworkInterface) nets.nextElement();
            Enumeration<InetAddress> ips = netint.getInetAddresses();
            //Iterate through all IP adddress
            while (ips.hasMoreElements()) {
                InetAddress ip = ips.nextElement();
                //Take the first address which isn't a loopback and is in the local address
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    LOGGER.info("Host IP Address: " + ip.getHostAddress());
                    ipAddr = ip.getHostAddress();
                    break;
                }
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.error("Error while getting hostName ", e);
    } catch (SocketException e) {
        LOGGER.error("Error while getting hostName ", e);
    }
    this.hostName = new JobHost(hostName, ipAddr, port);
}

From source file:totalcross.android.ConnectionManager4A.java

public static String getLocalIpAddress() {
    String ipv4 = null;//ww w .ja v a 2s.c o  m
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                // for getting IPV4 format
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress()))
                    return ipv4;
            }
        }
    } catch (Exception ex) {
        AndroidUtils.debug("IP Address" + ex.toString());
    }
    return null;
}

From source file:com.vmware.identity.idm.CommonUtil.java

private static String findInetAddress(Predicate<InetAddress> match) throws SocketException {
    String ipAddress = null;/*from  ww w.jav  a  2  s  .c  o m*/
    Enumeration<NetworkInterface> it = NetworkInterface.getNetworkInterfaces();

    while ((ipAddress == null) && it.hasMoreElements()) {
        NetworkInterface iface = it.nextElement();
        if ((!iface.isLoopback()) && (iface.isUp())) {
            Enumeration<InetAddress> it2 = iface.getInetAddresses();

            while (it2.hasMoreElements()) {
                InetAddress addr = it2.nextElement();
                if (match.matches(addr)) {
                    ipAddress = addr.getHostAddress();
                    break;
                }
            }
        }
    }

    return ipAddress;
}

From source file:com.hg.development.apps.messagenotifier_v1.Utils.Utility.java

/**
 *
 * @return adresse IP v4 actuelle du tlphone.
 * @throws SocketException/*ww  w . j a  v a2s . c o  m*/
 */
private String getLocalIpAddress() throws SocketException {
    String ipv4 = null;
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (interfaces.size() > 0) {
            for (NetworkInterface ni : interfaces) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());

                if (ialist.size() > 0) {
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress()
                                && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress()))
                            ;
                    }
                }

            }
        }

    } catch (SocketException ex) {
        throw ex;
    } finally {
        return ipv4;
    }
}