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:com.commonsware.android.webserver.template.WebServerService.java

private void raiseReadyEvent() {
    ServerStartedEvent event = new ServerStartedEvent();

    try {/*from   ww w. ja v  a2  s  . c  o  m*/
        for (Enumeration<NetworkInterface> enInterfaces = NetworkInterface.getNetworkInterfaces(); enInterfaces
                .hasMoreElements();) {
            NetworkInterface ni = enInterfaces.nextElement();

            for (Enumeration<InetAddress> enAddresses = ni.getInetAddresses(); enAddresses.hasMoreElements();) {
                InetAddress addr = enAddresses.nextElement();

                if (addr instanceof Inet4Address) {
                    event.addUrl("http://" + addr.getHostAddress() + ":4999");
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }

    EventBus.getDefault().removeAllStickyEvents();
    EventBus.getDefault().postSticky(event);
}

From source file:org.thingsplode.agent.monitors.providers.SystemComponentProvider.java

private List<Component> getNetwork() {
    try {//from w  ww .j  a va  2  s  .  c  om
        List<Component> networkComps = new ArrayList<>();
        Collections.list(NetworkInterface.getNetworkInterfaces()).forEach(n -> {
            try {

                CapabilityBuilder cb = Capability.CapabilityBuilder.newBuilder();
                cb.add("hw_address", Capability.Type.READ, true, Value.Type.TEXT,
                        Arrays.toString(n.getHardwareAddress())).add("hw_index", Capability.Type.READ, true,
                                Value.Type.TEXT, String.valueOf(n.getIndex()));

                if (n.getInetAddresses() != null) {
                    Collections.list(n.getInetAddresses()).forEach(ia -> {
                        cb.add("host_address", Capability.Type.READ, true, Value.Type.TEXT,
                                ia.getHostAddress());
                    });
                }

                Component nic = Component
                        .create(n.getDisplayName(), Component.Type.HARDWARE, EnabledState.ENABLED)
                        .putStatusInfo(n.isUp() ? StatusInfo.ONLINE : StatusInfo.OFFLINE)
                        .addCapabilities(cb.build());

                networkComps.add(nic);

            } catch (SocketException ex) {
                logAndSendError(ex);
            }
        });
        return networkComps;
    } catch (SocketException ex) {
        logAndSendError(ex);
        return null;
    }
}

From source file:net.centro.rtb.monitoringcenter.infos.NodeInfo.java

private static String detectPublicIpAddress() {
    Enumeration<NetworkInterface> networkInterfaces = null;
    try {/*from   w w  w  .ja va 2 s. c  o m*/
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.debug("Unable to obtain network interfaces!", e);
        return null;
    }

    for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        boolean isLoopback = false;
        try {
            isLoopback = networkInterface.isLoopback();
        } catch (SocketException e) {
            logger.debug("Unable to identify if a network interface is a loopback or not");
        }

        if (!isLoopback) {
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (Inet4Address.class.isInstance(inetAddress)) {
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isAnyLocalAddress()
                            && !inetAddress.isLinkLocalAddress() && !inetAddress.isSiteLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    }

    return null;
}

From source file:net.grinder.util.NetworkUtil.java

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
        throws SocketException {
    Enumeration<?> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        if (!i.isUp()) {
            continue;
        }//from   w w  w .ja  va  2s .co m
        for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

From source file:com.chiralBehaviors.slp.hive.configuration.BroadcastConfiguration.java

public Tuple<NetworkInterface, InetSocketAddress> getNetworkInterface() throws SocketException {
    if (networkInterface == null) {
        for (Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces(); intfs
                .hasMoreElements();) {//from  w w w  . j av a2 s .  c  o m
            NetworkInterface iface = intfs.nextElement();
            InetSocketAddress broadcastAddress = getBroadcastAddress(iface);
            if (broadcastAddress != null) {
                return new Tuple<NetworkInterface, InetSocketAddress>(iface, broadcastAddress);
            }
        }
        throw new IllegalStateException("No interface supporting broadcast was discovered");
    }
    NetworkInterface iface = NetworkInterface.getByName(networkInterface);
    if (iface == null) {
        throw new IllegalArgumentException(
                String.format("Cannot find network interface: %s ", networkInterface));
    }
    InetSocketAddress broadcastAddress = getBroadcastAddress(iface);
    if (broadcastAddress == null) {
        throw new IllegalStateException(
                String.format("The interface [%s] does not broadcast", networkInterface));
    }
    return new Tuple<NetworkInterface, InetSocketAddress>(iface, broadcastAddress);
}

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

private String getLocalIpAddress() {
    try {/*from  www . j  av a 2 s.co m*/
        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:hsyndicate.utils.IPUtils.java

public static Collection<String> getIPAddress() {
    if (!cachedIPAddr.isEmpty()) {
        return Collections.unmodifiableCollection(cachedIPAddr);
    } else {/*from  w w  w. j  av a2  s .c  om*/
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();
                    if (!i.isLoopbackAddress()) {
                        String hostAddress = i.getHostAddress();
                        cachedIPAddr.add(hostAddress);
                    }
                }
            }
        } catch (SocketException ex) {
            LOG.error("Exception occurred while scanning local interfaces", ex);
        }

        return Collections.unmodifiableCollection(cachedIPAddr);
    }
}

From source file:org.pentaho.platform.util.UUIDUtil.java

public static String getActiveNetworkMacAddress() throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface nif = interfaces.nextElement();
        // Obvious what the next IF is doing, but it must be connected, non-PPP, non-loopback, and non-virtual
        if ((nif.isUp()) && (!nif.isPointToPoint()) && (!nif.isLoopback()) && (!nif.isVirtual())) {
            return getInterfaceInfo(nif);
        }//w ww  .  ja v a 2s  .  co  m
    }
    return null;
}

From source file:org.openbaton.nfvo.system.SystemStartup.java

@Override
public void run(String... args) throws Exception {
    log.info("Initializing OpenBaton");

    log.debug(Arrays.asList(args).toString());

    propFileLocation = propFileLocation.replace("file:", "");
    log.debug("Property file: " + propFileLocation);

    InputStream is = new FileInputStream(propFileLocation);
    Properties properties = new Properties();
    properties.load(is);//ww  w .ja va  2  s.  c  om

    log.debug("Config Values are: " + properties.values());

    Configuration c = new Configuration();

    c.setName("system");
    c.setConfigurationParameters(new HashSet<ConfigurationParameter>());

    /**
     * Adding properties from file
     */
    for (Entry<Object, Object> entry : properties.entrySet()) {
        ConfigurationParameter cp = new ConfigurationParameter();
        cp.setConfKey((String) entry.getKey());
        cp.setValue((String) entry.getValue());
        c.getConfigurationParameters().add(cp);
    }

    /**
     * Adding system properties
     */
    Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netint : Collections.list(nets)) {
        ConfigurationParameter cp = new ConfigurationParameter();
        log.trace("Display name: " + netint.getDisplayName());
        log.trace("Name: " + netint.getName());
        cp.setConfKey("ip-" + netint.getName().replaceAll("\\s", ""));
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            if (inetAddress.getHostAddress().contains(".")) {
                log.trace("InetAddress: " + inetAddress.getHostAddress());
                cp.setValue(inetAddress.getHostAddress());
            }
        }
        log.trace("");
        c.getConfigurationParameters().add(cp);
    }

    configurationRepository.save(c);

    if (installPlugin) {
        startPlugins(pluginDir);
    }
}

From source file:com.vinexs.tool.NetworkManager.java

public static InetAddress getInetAddress(Context context) {
    if (haveNetwork(context)) {
        return null;
    }/*  www.  ja  v a  2  s  . com*/
    if (isWifiNetwork(context)) {
        int ipAddress = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                .getIpAddress();
        if (ipAddress == 0) {
            return null;
        }
        return intToInet(ipAddress);
    }
    try {
        Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces();
        while (netinterfaces.hasMoreElements()) {
            NetworkInterface netinterface = netinterfaces.nextElement();
            Enumeration<InetAddress> adresses = netinterface.getInetAddresses();
            while (adresses.hasMoreElements()) {
                InetAddress address = adresses.nextElement();
                if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
                    return address;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}