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.mgmtp.perfload.perfmon.util.PerfMonUtils.java

/**
 * Gets all network interfaces of the localhost.
 * //from  ww  w .  java 2  s  . c  o  m
 * @return a list of {@link NetworkInterface} objects
 */
public static List<NetworkInterface> getNetworkInterfaces() throws SocketException {
    List<NetworkInterface> niList = new ArrayList<NetworkInterface>();
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();
        niList.add(intf);
    }
    return niList;
}

From source file:org.openhab.binding.network.internal.utils.NetworkUtils.java

/**
 * Get a set of all interface names.//from  w w  w.j a va2s  .c  o m
 *
 * @return Set of interface names
 */
public Set<String> getInterfaceNames() {
    Set<String> result = new HashSet<>();

    try {
        // For each interface ...
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface networkInterface = en.nextElement();
            if (!networkInterface.isLoopback()) {
                result.add(networkInterface.getName());
            }
        }
    } catch (SocketException ignored) {
        // If we are not allowed to enumerate, we return an empty result set.
    }

    return result;
}

From source file:org.tinymediamanager.core.License.java

/**
 * returns ALL found MAC address of this instance
 * /*  w  w w.  j  a  v a  2  s .co m*/
 * @return MAC or empty string
 */
private static List<String> getAllMacAddresses() {
    List<String> m = new ArrayList<>();
    m.add(UNKNOWN_MAC); // lic generated with empty mac, but java cannot handle this :/ use fake mac for further checks
    try {
        for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
            NetworkInterface ni = e.nextElement();
            String macAddress = formatMac(ni.getHardwareAddress());
            if (macAddress != null && !macAddress.isEmpty()) {
                m.add(macAddress);
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error getting MAC of all interfaces");
    }
    return m;
}

From source file:org.jumpmind.util.AppUtils.java

public static String getIpAddress() {
    String ipAddress = System.getProperty(SYSPROP_IP_ADDRESS, UNKNOWN);
    if (UNKNOWN.equals(ipAddress)) {
        try {/*from w ww  .ja  v a2s  .co m*/
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        ipAddress = inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
            log.warn("", ex);
        } finally {
        }
    }

    if (UNKNOWN.equals(ipAddress)) {
        try {
            ipAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ex) {
            log.warn("", ex);
            ipAddress = "127.0.0.1";
        }
    }
    return ipAddress;
}

From source file:org.openhab.binding.russound.internal.discovery.RioSystemDiscovery.java

/**
 * Starts the scan. For each network interface (that is up and not a loopback), all addresses will be iterated
 * and checked for something open on port 9621. If that port is open, a russound controller "type" command will be
 * issued. If the response is a correct pattern, we assume it's a rio system device and will emit a
 * {{@link #thingDiscovered(DiscoveryResult)}
 */// w w w.  jav a  2s.  com
@Override
protected void startScan() {
    final List<NetworkInterface> interfaces;
    try {
        interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    } catch (SocketException e1) {
        logger.debug("Exception getting network interfaces: {}", e1.getMessage(), e1);
        return;
    }

    nbrNetworkInterfacesScanning = interfaces.size();
    executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);

    for (final NetworkInterface networkInterface : interfaces) {
        try {
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
        } catch (SocketException e) {
            continue;
        }

        for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                .hasNext();) {
            final InterfaceAddress interfaceAddress = it.next();

            // don't bother with ipv6 addresses (russound doesn't support)
            if (interfaceAddress.getAddress() instanceof Inet6Address) {
                continue;
            }

            final String subnetRange = interfaceAddress.getAddress().getHostAddress() + "/"
                    + interfaceAddress.getNetworkPrefixLength();

            logger.debug("Scanning subnet: {}", subnetRange);
            final SubnetUtils utils = new SubnetUtils(subnetRange);

            final String[] addresses = utils.getInfo().getAllAddresses();

            for (final String address : addresses) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        scanAddress(address);
                    }
                });
            }
        }
    }

    // Finishes the scan and cleans up
    stopScan();
}

From source file:es.eucm.eadventure.editor.plugin.vignette.ServerProxy.java

public String getMac() {
    if (mac == null) {
        try {//from ww  w. ja v  a2  s  .co  m
            byte[] macBytes = NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress();
            mac = new String(Hex.encodeHex(macBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return mac;
}

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Tell controller that we're ready to handle channels.
 *//*from   w  w w  .  j ava2s .  c o m*/
public void run() {
    try {
        //get the configuration from json file
        List<OSPFArea> areas = getConfiguration();
        //get the connected interfaces
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        // Check NetworkInterfaces and area-config have same IP Address
        for (NetworkInterface netInt : Collections.list(nets)) {
            // if the interface is up & not loopback
            if (!netInt.isUp() && !netInt.isLoopback()) {
                continue;
            }
            //get all the InetAddresses
            Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                String ipAddress = inetAddress.getHostAddress();
                //Search for the address in all configured areas interfaces
                for (OSPFArea area : areas) {
                    for (OSPFInterface ospfIf : area.getInterfacesLst()) {
                        String ipFromConfig = ospfIf.getIpAddress();
                        if (ipFromConfig.trim().equals(ipAddress.trim())) {
                            log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress,
                                    area.getAreaID());
                            // if same IP address create
                            try {
                                log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort);

                                final ServerBootstrap bootstrap = createServerBootStrap();
                                bootstrap.setOption("reuseAddr", true);
                                bootstrap.setOption("child.keepAlive", true);
                                bootstrap.setOption("child.tcpNoDelay", true);
                                bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);

                                //Set the interface name in ospfInterface
                                ospfIf.setInterfaceName(netInt.getDisplayName());
                                //netInt.get
                                // passing OSPFArea and interface to pipelinefactory
                                ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area,
                                        ospfIf);
                                bootstrap.setPipelineFactory(pfact);
                                InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress),
                                        ospfPort);

                                cg = new DefaultChannelGroup();
                                cg.add(bootstrap.bind(sa));

                                log.debug("Listening for connections on {}", sa);
                                //For testing. remove this
                                interfc = ospfIf;

                                //Start aging process
                                area.initializeDB();
                                area.initializeArea();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("Error::Controller:: {}", e.getMessage());
    }
}

From source file:com.vaadin.tests.tb3.PrivateTB3Configuration.java

/**
 * Tries to automatically determine the IP address of the machine the test
 * is running on./*from w  w  w  .  j av  a 2  s  . com*/
 * 
 * @return An IP address of one of the network interfaces in the machine.
 * @throws RuntimeException
 *             if there was an error or no IP was found
 */
private static String findAutoHostname() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nwInterface = interfaces.nextElement();
            if (!nwInterface.isUp() || nwInterface.isLoopback() || nwInterface.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address.isLoopbackAddress()) {
                    continue;
                }
                if (address.isSiteLocalAddress()) {
                    return address.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Could not enumerate ");
    }

    throw new RuntimeException("No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}

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   ww w.j a v  a2  s .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:com.frostwire.android.gui.NetworkManager.java

private static List<String> getInterfaceNames() {
    List<String> names = new LinkedList<>();
    try {/* ww w. ja v a2 s  . c  o m*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        if (networkInterfaces != null) {
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                String name = networkInterface.getName();
                if (name != null) {
                    names.add(name);
                }
            }
        }
    } catch (Throwable e) {
        // ignore
        // important, but no need to crash the app
    }

    return names;
}