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.limegroup.gnutella.gui.DaapManager.java

/**
 * Starts the DAAP Server//from   ww  w.  j  a  va  2s .  c  o m
 */
public synchronized void start() throws IOException {

    if (!isServerRunning()) {

        try {

            InetAddress addr = InetAddress.getLocalHost();

            if (addr.isLoopbackAddress() || !(addr instanceof Inet4Address)) {
                addr = null;
                Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
                if (interfaces != null) {
                    while (addr == null && interfaces.hasMoreElements()) {
                        NetworkInterface nif = (NetworkInterface) interfaces.nextElement();
                        Enumeration addresses = nif.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress address = (InetAddress) addresses.nextElement();
                            if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                                addr = address;
                                break;
                            }
                        }
                    }
                }
            }

            if (addr == null) {
                stop();
                // No valid IP address -- just ignore, since
                // it's probably the user isn't connected to the
                // internet.  Next time they start, it might work.
                return;
            }

            rendezvous = new RendezvousService(addr);

            map = new SongURNMap();

            maxPlaylistSize = DaapSettings.DAAP_MAX_LIBRARY_SIZE.getValue();

            String name = DaapSettings.DAAP_LIBRARY_NAME.getValue();
            int revisions = DaapSettings.DAAP_LIBRARY_REVISIONS.getValue();
            boolean useLibraryGC = DaapSettings.DAAP_LIBRARY_GC.getValue();
            library = new Library(name, revisions, useLibraryGC);

            database = new Database(name);
            whatsNew = new Playlist(GUIMediator.getStringResource("SEARCH_TYPE_WHATSNEW"));
            creativecommons = new Playlist(GUIMediator.getStringResource("LICENSE_CC"));
            videos = new Playlist(GUIMediator.getStringResource("MEDIA_VIDEO"));

            Transaction txn = library.open(false);
            library.add(txn, database);
            database.add(txn, creativecommons);
            database.add(txn, whatsNew);
            database.add(txn, videos);
            creativecommons.setSmartPlaylist(txn, true);
            whatsNew.setSmartPlaylist(txn, true);
            videos.setSmartPlaylist(txn, true);
            txn.commit();

            LimeConfig config = new LimeConfig(addr);

            final boolean NIO = DaapSettings.DAAP_USE_NIO.getValue();

            server = DaapServerFactory.createServer(library, config, NIO);

            server.setAuthenticator(new LimeAuthenticator());
            server.setStreamSource(new LimeStreamSource());
            server.setFilter(new LimeFilter());

            if (!NIO) {
                server.setThreadFactory(new LimeThreadFactory());
            }

            final int maxAttempts = 10;

            for (int i = 0; i < maxAttempts; i++) {
                try {
                    server.bind();
                    break;
                } catch (BindException bindErr) {
                    if (i < (maxAttempts - 1)) {
                        // try next port...
                        config.nextPort();
                    } else {
                        throw bindErr;
                    }
                }
            }

            Thread serverThread = new ManagedThread(server, "DaapServerThread") {
                protected void managedRun() {
                    try {
                        super.managedRun();
                    } catch (Throwable t) {
                        DaapManager.this.stop();
                        if (!handleError(t)) {
                            GUIMediator.showError("ERROR_DAAP_RUN_ERROR");
                            DaapSettings.DAAP_ENABLED.setValue(false);
                            if (t instanceof RuntimeException)
                                throw (RuntimeException) t;
                            throw new RuntimeException(t);
                        }
                    }
                }
            };

            serverThread.setDaemon(true);
            serverThread.start();

            rendezvous.registerService();

        } catch (IOException err) {
            stop();
            throw err;
        }
    }
}

From source file:com.adito.setup.forms.SystemInfoForm.java

/**
 * Get a list (as strings) of the nwrok interfaces that are available
 * on this host.//  w  ww.  ja v  a  2  s .c o  m
 *   
 * TODO This should be the interfaces that Adito is using.
 *   
 * @return network interfaces
 */
public List getNetworkInterfaces() {
    Enumeration e = null;
    try {
        List niList = new ArrayList();
        e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface netface = (NetworkInterface) e.nextElement();
            Enumeration e2 = netface.getInetAddresses();
            while (e2.hasMoreElements()) {
                InetAddress ip = (InetAddress) e2.nextElement();
                niList.add(netface.getName() + "=" + ip.toString());
            }
        }
        return niList;
    } catch (SocketException e1) {
        return new ArrayList();
    }
}

From source file:ubicrypt.core.Utils.java

public static int deviceId() {
    try {//from   ww w  .  j a v a2 s  . co m
        final Enumeration<NetworkInterface> it = NetworkInterface.getNetworkInterfaces();
        int ret = 0;
        while (it.hasMoreElements() && ret == 0) {
            ret = Arrays.hashCode(it.nextElement().getHardwareAddress());
        }
        return ret;
    } catch (final SocketException e) {
        Throwables.propagate(e);
    }
    return -1;
}

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

public List<NetworkInterface> getNetworkInterfaces(InetAddressAcceptor aAcceptor) throws SocketException {
    List<NetworkInterface> result = new ArrayList<NetworkInterface>();
    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  ww.  j  a v a 2s .  co  m*/
            }
            result.add(networkInterface);
        } 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:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Get the server addresses from interfaces.
 *///from   w w  w  .  j a  v  a2s . c  o  m
public static String getHostAddresses() {
    try {
        Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        // Copy from enumeration to addresses vector, but filter loopback addresses
        ArrayList addresses = new ArrayList();
        while (interfaceEnumeration.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface) interfaceEnumeration.nextElement();
            // Remove loopback addresses
            Enumeration addressEnumeration = intf.getInetAddresses();
            while (addressEnumeration.hasMoreElements()) {
                InetAddress address = (InetAddress) addressEnumeration.nextElement();
                // Insert to addresses only if not loopback and not link local
                if ((!address.isLoopbackAddress()) && (!address.isLinkLocalAddress()))
                    addresses.add(address);
            }
        }
        // Pick one address from the remaining address space
        logger.debug("server available local addresses: " + addresses);
        // Now, multiple addresses are in the list, so copy all of them
        // into the result string.
        StringBuffer ips = new StringBuffer();
        for (int i = 0; i < addresses.size(); i++) {
            InetAddress address = (InetAddress) addresses.get(i);
            if (ips.length() > 0)
                ips.append(",");
            ips.append(address.getHostAddress());
        }
        return ips.toString();
    } catch (StoreException e) {
        throw e;
    } catch (Exception e) {
        throw new StoreException("exception while determining server address", e);
    }
}

From source file:at.tugraz.ist.akm.networkInterface.WifiIpAddress.java

private String readIP4AddressOfEmulator() throws SocketException {
    String inet4Address = "0.0.0.0";

    for (Enumeration<NetworkInterface> iter = NetworkInterface.getNetworkInterfaces(); iter
            .hasMoreElements();) {//from  w  ww  .j  a v  a  2s. c om
        NetworkInterface nic = iter.nextElement();

        if (nic.getName().startsWith("eth")) {
            Enumeration<InetAddress> addresses = nic.getInetAddresses();
            addresses.nextElement(); // skip first
            if (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();

                String concreteAddressString = address.getHostAddress().toUpperCase(Locale.getDefault());
                if (InetAddressUtils.isIPv4Address(concreteAddressString)) {
                    inet4Address = concreteAddressString;
                }
            }
        }
    }
    return inet4Address;
}

From source file:com.castlemock.web.basis.web.mvc.controller.AbstractController.java

/**
 * The method returns the local address (Not link local address, not loopback address) which the server is deployed on.
 * If the method does not find any INet4Address that is neither link local address and loopback address, the method
 * will return the the address 127.0.0.1
 * @return Returns the local address or 127.0.0.1 if no address was found
 * @throws SocketException Upon failing to extract network interfaces
 *//*from  w  ww  .j  av  a2s.  com*/
public String getHostAddress() throws SocketException {
    if (endpointAddress != null && !endpointAddress.isEmpty()) {
        return endpointAddress;
    }

    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaces.nextElement();
        final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            final InetAddress address = addresses.nextElement();
            if (!address.isLinkLocalAddress() && !address.isLoopbackAddress()
                    && address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
    }

    return LOCAL_ADDRESS;
}

From source file:org.jkcsoft.java.util.JavaHelper.java

public static InetAddress getUsefulInetAddr() throws UnknownHostException {
    InetAddress returnInetAddr = InetAddress.getLocalHost();
    int usefulCount = 0;
    try {/* ww  w.  j  a  v a 2s . c  o  m*/
        Enumeration niEnum = NetworkInterface.getNetworkInterfaces();
        while (niEnum.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) niEnum.nextElement();
            Enumeration ieEnum = ni.getInetAddresses();
            while (ieEnum.hasMoreElements()) {
                InetAddress inetAddr = InetAddress.getLocalHost();
                inetAddr = (InetAddress) ieEnum.nextElement();
                log.debug("NIC [" + ni.getDisplayName() + "]" + " Addr hn=[" + inetAddr.getHostName() + "]"
                        + " chn=[" + inetAddr.getCanonicalHostName() + "]" + " ha=[" + inetAddr.getHostAddress()
                        + "]");
                // hack to skip addresses often provided by Linux...
                if (!"127.0.0.1".equals(inetAddr.getHostAddress())
                        && inetAddr.getHostAddress().indexOf(':') == -1) {
                    if (usefulCount == 0)
                        returnInetAddr = inetAddr;
                    usefulCount++;
                } else {
                    // 
                }
            }
        }
    } catch (SocketException e) {
        log.error("getHostName", e);
    }

    if (usefulCount == 0) {
        log.warn("Only the loopback InetAddress could be found");
    }
    if (usefulCount > 1) {
        log.warn("More than one non-loopback InetAddrss was found; using the first one found.");
    }

    log.debug("Returning inet addr [" + returnInetAddr.toString() + "]");
    return returnInetAddr;
}

From source file:org.wso2.bam.integration.tests.agents.KPIAgent.java

private static InetAddress getLocalHostAddress() throws SocketException {
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        Enumeration<InetAddress> addresses = iface.getInetAddresses();

        while (addresses.hasMoreElements()) {
            InetAddress addr = addresses.nextElement();
            if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                return addr;
            }/*from www.  j  av  a 2s .  c  o m*/
        }
    }

    return null;
}

From source file:net.pocketmine.server.HomeActivity.java

public static String getIPAddress(boolean useIPv4) {
    try {/*from  w ww .  java  2  s. 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(Locale.US);
                    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) {
    }
    return ha.getResources().getString(R.string.unknown);
}