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:to.sven.androidrccar.host.communication.impl.SocketConnector.java

/**
 * Returns the first non-local IPv4 address of the device. 
 * @return IPv4 address as String or unknown, if no address is found.
 *//*from  w  w w .  j  a v  a  2s  .c  o m*/
private String getLocalIpAddress() {
    try {
        for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InetAddress address : Collections.list(iface.getInetAddresses())) {
                if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(address.getHostAddress())) {
                    return address.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return dc.getContext().getString(android.R.string.unknownName);
}

From source file:org.springframework.cloud.commons.util.InetUtils.java

public InetAddress findFirstNonLoopbackAddress() {
    InetAddress result = null;//from ww w .j  a  v  a  2  s. c  o m
    try {
        int lowest = Integer.MAX_VALUE;
        for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics
                .hasMoreElements();) {
            NetworkInterface ifc = nics.nextElement();
            if (ifc.isUp()) {
                log.trace("Testing interface: " + ifc.getDisplayName());
                if (ifc.getIndex() < lowest || result == null) {
                    lowest = ifc.getIndex();
                } else if (result != null) {
                    continue;
                }

                // @formatter:off
                if (!ignoreInterface(ifc.getDisplayName())) {
                    for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) {
                        InetAddress address = addrs.nextElement();
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()
                                && !ignoreAddress(address)) {
                            log.trace("Found non-loopback interface: " + ifc.getDisplayName());
                            result = address;
                        }
                    }
                }
                // @formatter:on
            }
        }
    } catch (IOException ex) {
        log.error("Cannot get first non-loopback address", ex);
    }

    if (result != null) {
        return result;
    }

    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        log.warn("Unable to retrieve localhost");
    }

    return null;
}

From source file:org.apache.spark.simr.Simr.java

/**
 * @return The IP of the first network interface on this machine as a string, null in the case
 * of an exception from the underlying network interface.
 *///from ww w. j  a v  a2s  .c om
public String getLocalIP() {
    String ip;
    int pickIfaceNum = conf.getInt("simr_interface", 0);

    int currIface = 0;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();

            if (iface.isLoopback() || !iface.isUp())
                continue;

            if (currIface++ >= pickIfaceNum) {
                Enumeration<InetAddress> addresses = iface.getInetAddresses();

                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet4Address) {
                        ip = addr.getHostAddress();
                        return ip;
                    }
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.zz.cluster4spring.localinfo.DefaultLocalNetworkInfoProvider.java

public List<InetAddress> getLocalAddresses(InetAddressAcceptor aAcceptor) throws SocketException {
    List<InetAddress> result = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        if (aAcceptor.acceptNetworkInterface(networkInterface)) {
            if (fLog.isInfoEnabled()) {
                String name = networkInterface.getName();
                String displayName = networkInterface.getDisplayName();
                fLog.info(MessageFormat.format(
                        "Discovered NetworkInterface - ACCEPTED. Name:[{0}]. Display Name:[{1}]", name,
                        displayName));//from   w  w  w.j  ava 2s .c o  m
            }
            collectInterfaceAddresses(networkInterface, result, aAcceptor);
        } else {
            if (fLog.isInfoEnabled()) {
                String name = networkInterface.getName();
                String displayName = networkInterface.getDisplayName();
                fLog.info(MessageFormat.format(
                        "Discovered NetworkInterface - SKIPPED. Name:[{0}]. Display Name:[{1}]", name,
                        displayName));
            }
        }
    }
    return result;
}

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * returns the canonical host name. This assumes a unique host name for
 * each machine in the cluster does not apply.
 * FixMe: In local cloud environment (local eucalyptus in system mode)
 * where the DNS server is not running, this might be an issue.
 * @return The first IPv4 address found for any interface that is up and
 * running.//from   w  w w  .  j av  a2 s .c om
 */
public static String getIpAddress() {
    String ip = null;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        LOGGER.error("Getting ip");

        while (interfaces.hasMoreElements()) {
            LOGGER.error("Next iface");
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                ip = currentAddr.getHostAddress();
            }
        }
    } catch (SocketException e) {
        LOGGER.error("Error occurred while retrieving hostname" + e.getMessage());
        throw new RuntimeException("Error occurred while " + "retrieving hostname" + e.getMessage());
    }
    return ip;
}

From source file:com.cats.version.utils.Utils.java

public static String getLocalHostIp() {
    String regex = "[\\d]+.[\\d]+.[\\d]+.[\\d]+";
    Enumeration<?> e = null;
    try {//from w  w w.j a  va 2s. co m
        e = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e1) {
        e1.printStackTrace();
    }
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<?> ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress i = (InetAddress) ee.nextElement();
            String ip = i.getHostAddress();
            if (ip.matches(regex) && !ip.equals("127.0.0.1")) {
                return ip;
            }
        }
    }
    return null;
}

From source file:org.springframework.vault.authentication.MacAddressUserId.java

@Override
public String createUserId() {

    try {//from  www. java  2 s.  com

        NetworkInterface networkInterface = null;
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (StringUtils.hasText(networkInterfaceHint)) {

            try {
                networkInterface = getNetworkInterface(Integer.parseInt(networkInterfaceHint), interfaces);
            } catch (NumberFormatException e) {
                networkInterface = getNetworkInterface((networkInterfaceHint), interfaces);
            }
        }

        if (networkInterface == null) {

            if (StringUtils.hasText(networkInterfaceHint)) {
                log.warn(String.format("Did not find a NetworkInterface applying hint %s",
                        networkInterfaceHint));
            }

            InetAddress localHost = InetAddress.getLocalHost();
            networkInterface = NetworkInterface.getByInetAddress(localHost);

            if (networkInterface == null) {
                throw new IllegalStateException(
                        String.format("Cannot determine NetworkInterface for %s", localHost));
            }
        }

        byte[] mac = networkInterface.getHardwareAddress();
        if (mac == null) {
            throw new IllegalStateException(
                    String.format("Network interface %s has no hardware address", networkInterface.getName()));
        }

        return Sha256.toSha256(Sha256.toHexString(mac));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:de.madvertise.android.sdk.MadUtil.java

/**
 * Fetch the address of the enabled interface
 * /* w w w .j  a v a2  s. com*/
 * @return ip address as string
 */
protected static String getLocalIpAddress() {
    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();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        if (PRINT_LOG)
            Log.d(MadUtil.LOG, ex.toString());
    }
    return "";
}

From source file:org.trafodion.rest.zookeeper.ZkQuorumPeer.java

static void writeMyID(Properties properties) throws IOException {
    long myId = -1;

    Configuration conf = RestConfiguration.create();
    String myAddress = Strings//  www .j  av a  2s  .c  om
            .domainNamePointerToHostName(DNS.getDefaultHost(conf.get("rest.zookeeper.dns.interface", "default"),
                    conf.get("rest.zookeeper.dns.nameserver", "default")));

    List<String> ips = new ArrayList<String>();

    // Add what could be the best (configured) match
    ips.add(myAddress.contains(".") ? myAddress : StringUtils.simpleHostname(myAddress));

    // For all nics get all hostnames and IPs
    Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        Enumeration<?> rawAdrs = ((NetworkInterface) nics.nextElement()).getInetAddresses();
        while (rawAdrs.hasMoreElements()) {
            InetAddress inet = (InetAddress) rawAdrs.nextElement();
            ips.add(StringUtils.simpleHostname(inet.getHostName()));
            ips.add(inet.getHostAddress());
        }
    }

    for (Entry<Object, Object> entry : properties.entrySet()) {
        String key = entry.getKey().toString().trim();
        String value = entry.getValue().toString().trim();
        if (key.startsWith("server.")) {
            int dot = key.indexOf('.');
            long id = Long.parseLong(key.substring(dot + 1));
            String[] parts = value.split(":");
            String address = parts[0];
            if (addressIsLocalHost(address) || ips.contains(address)) {
                myId = id;
                break;
            }
        }
    }

    // Set the max session timeout from the provided client-side timeout
    properties.setProperty("maxSessionTimeout", conf.get("zookeeper.session.timeout", "180000"));

    if (myId == -1) {
        throw new IOException(
                "Could not find my address: " + myAddress + " in list of ZooKeeper quorum servers");
    }

    String dataDirStr = properties.get("dataDir").toString().trim();
    File dataDir = new File(dataDirStr);
    if (!dataDir.isDirectory()) {
        if (!dataDir.mkdirs()) {
            throw new IOException("Unable to create data dir " + dataDir);
        }
    }

    File myIdFile = new File(dataDir, "myid");
    PrintWriter w = new PrintWriter(myIdFile);
    w.println(myId);
    w.close();
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {/*from   w  ww  .  j a v  a 2s. c  o  m*/
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}