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.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java

@Override
protected void startScan() {
    stopScan();/*from   ww w.  java2s  .co m*/

    logger.debug("Start scan for LOGO! bridge");

    Enumeration<NetworkInterface> devices = null;
    try {
        devices = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException exception) {
        logger.warn("LOGO! bridge discovering: {}.", exception.toString());
    }

    Set<String> addresses = new TreeSet<>();
    while ((devices != null) && devices.hasMoreElements()) {
        NetworkInterface device = devices.nextElement();
        try {
            if (!device.isUp() || device.isLoopback()) {
                continue;
            }
        } catch (SocketException exception) {
            logger.warn("LOGO! bridge discovering: {}.", exception.toString());
        }
        for (InterfaceAddress iface : device.getInterfaceAddresses()) {
            InetAddress address = iface.getAddress();
            if (address instanceof Inet4Address) {
                String prefix = String.valueOf(iface.getNetworkPrefixLength());
                SubnetUtils utilities = new SubnetUtils(address.getHostAddress() + "/" + prefix);
                addresses.addAll(Arrays.asList(utilities.getInfo().getAllAddresses()));
            }
        }
    }

    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (String address : addresses) {
        try {
            executor.execute(new Runner(address));
        } catch (RejectedExecutionException exception) {
            logger.warn("LOGO! bridge discovering: {}.", exception.toString());
        }
    }

    try {
        executor.awaitTermination(CONNECTION_TIMEOUT * addresses.size(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException exception) {
        logger.warn("LOGO! bridge discovering: {}.", exception.toString());
    }
    executor.shutdown();

    stopScan();
}

From source file:com.jean.farCam.SettingsActivity.java

public static String getIPAddress() {
    try {/*from   w w  w  .  j av a2 s  .com*/
        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();
                    if (InetAddressUtils.isIPv4Address(sAddr)) {
                        return sAddr;
                    }
                }
            }
        }
    } catch (Exception ex) {
    }
    return "";
}

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  w w  w.j a  va  2s  .c om*/
                result.append(addresses.nextElement().getHostAddress());
            }
        }
    }
    return result.toString();
}

From source file:io.tilt.minka.domain.NetworkShardIDImpl.java

private InetAddress findSiteAddress(final Config config) {
    InetAddress fallback = null;//  w  w w  .java 2s  . c o  m
    try {
        final String niName = config.getFollowerUseNetworkInterfase();
        logger.info("{}: Looking for configured network interfase: {}", getClass().getSimpleName(), niName);
        final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            final NetworkInterface ni = nis.nextElement();
            if (niName.contains(ni.getName())) {
                logger.info("{}: Interfase found: {}, looking for a Site address..", getClass().getSimpleName(),
                        ni.getName());
                final Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    final InetAddress ia = ias.nextElement();
                    if (ia.isSiteLocalAddress()) {
                        logger.info("{}: Host site address found: {}:{} with HostName {}",
                                getClass().getSimpleName(), ia.getHostAddress(), config.getBrokerServerPort(),
                                ia.getHostName());
                        return ia;
                    } else {
                        fallback = ia;
                        logger.warn("{}: Specified interfase: {} is not a site address!!, "
                                + "you should specify a non local-only valid interfase !! where's your lan?",
                                getClass().getSimpleName(), ia.getHostAddress());
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("{}: Cannot build shard id value with hostname", getClass().getSimpleName(), e);
    }
    logger.error("{}: Site network interfase not found !", getClass().getSimpleName());
    return fallback;
}

From source file:com.commonsware.android.webserver.secure.WebServerService.java

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

    try {//from  w  w  w.  j a  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" + rootPath + "/");
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }

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

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  ww  .  j  a v a  2 s.  co m
        }
    }
    return null;
}

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

public List<InetAddress> getAvailableAddresses() {
    List<InetAddress> result = Lists.newArrayList();
    try {//from  ww  w.  j  a v  a 2  s  . 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:stargate.commons.utils.IPUtils.java

public static Collection<String> getIPAddress() {
    if (!cached_ip_addr.isEmpty()) {
        return Collections.unmodifiableCollection(cached_ip_addr);
    } else {/*from  w w w. j  a  va 2s .  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();
                        cached_ip_addr.add(hostAddress);
                    }
                }
            }
        } catch (SocketException ex) {
            LOG.error("Exception occurred while scanning local interfaces", ex);
        }

        return Collections.unmodifiableCollection(cached_ip_addr);
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
public void init(ServletConfig config) {
    /// List possible local address
    try {//from  ww w.j  ava  2 s .  c om
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual())
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr instanceof Inet4Address)
                    ourIPs.add(current_addr.getHostAddress());
            }
        }
    } catch (Exception e) {
    }

    servContext = config.getServletContext();
    backend = config.getServletContext().getInitParameter("backendserver");
    server = config.getServletContext().getInitParameter("fileserver");
    try {
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.nebula.framework.core.HeartbeatWorker.java

private void acquireIp() {
    Enumeration<NetworkInterface> net = null;
    try {/*from w  w w . ja  v  a2s.c  o m*/
        net = NetworkInterface.getNetworkInterfaces();

        while (net.hasMoreElements()) {
            NetworkInterface element = net.nextElement();
            Enumeration<InetAddress> addresses = element.getInetAddresses();
            while (addresses.hasMoreElements()) {

                InetAddress ipAddress = addresses.nextElement();
                if (ipAddress instanceof Inet4Address) {

                    if (ipAddress.isSiteLocalAddress()) {
                        ip = ipAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        // ignore
    }
}