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:ch.cyberduck.core.socket.NetworkInterfaceAwareSocketFactory.java

private NetworkInterface findIPv6Interface(Inet6Address address) throws IOException {
    if (blacklisted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Ignore IP6 default network interface setup with empty blacklist");
        }//from   w  ww.  j  a  v a  2  s .c  om
        return null;
    }
    if (address.getScopeId() != 0) {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Ignore IP6 default network interface setup for address with scope identifier %d",
                    address.getScopeId()));
        }
        return null;
    }
    // If we find an interface name en0 that supports IPv6 make it the default.
    // We must use the index of the network interface. Referencing the interface by name will still
    // set the scope id to '0' referencing the awdl0 interface that is first in the list of enumerated
    // network interfaces instead of its correct index in <code>java.net.Inet6Address</code>
    // Use private API to defer the numeric format for the address
    List<Integer> indexes = new ArrayList<Integer>();
    final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
    while (enumeration.hasMoreElements()) {
        indexes.add(enumeration.nextElement().getIndex());
    }
    for (Integer index : indexes) {
        final NetworkInterface n = NetworkInterface.getByIndex(index);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Evaluate interface with %s index %d", n, index));
        }
        if (!n.isUp()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Ignore interface %s not up", n));
            }
            continue;
        }
        if (blacklisted.contains(n.getName())) {
            log.warn(String.format("Ignore network interface %s disabled with blacklist", n));
            continue;
        }
        for (InterfaceAddress i : n.getInterfaceAddresses()) {
            if (i.getAddress() instanceof Inet6Address) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Selected network interface %s", n));
                }
                return n;
            }
        }
        log.warn(String.format("No IPv6 for interface %s", n));
    }
    log.warn("No network interface found for IPv6");
    return null;
}

From source file:org.apache.cassandra.hadoop.ColumnFamilyRecordReader.java

private String getLocation() {
    ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
    try {/*from  w ww . jav  a  2 s .  c  o m*/
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        while (nets.hasMoreElements())
            localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses()));
    } catch (SocketException e) {
        throw new AssertionError(e);
    }

    for (InetAddress address : localAddresses) {
        for (String location : split.getLocations()) {
            InetAddress locationAddress = null;
            try {
                locationAddress = InetAddress.getByName(location);
            } catch (UnknownHostException e) {
                throw new AssertionError(e);
            }
            if (address.equals(locationAddress)) {
                return location;
            }
        }
    }
    return split.getLocations()[0];
}

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {/*from www  .  j a  v  a 2  s  .co m*/
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

public static final InetAddress getLocalInetAddress() {
    InetAddress selectedInetAddress = null;
    try {//  www  .ja v  a2s .  c om
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            if (intf.isUp()) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        if (inetAddress instanceof Inet4Address) { // only
                            // want
                            // ipv4
                            // address
                            if (inetAddress.getHostAddress().toString().charAt(0) != '0') {
                                if (selectedInetAddress == null) {
                                    selectedInetAddress = inetAddress;
                                } else if (intf.getName().startsWith("eth")) { // prefer
                                    // wired
                                    // interface
                                    selectedInetAddress = inetAddress;
                                }
                            }
                        }
                    }
                }
            }
        }
        return selectedInetAddress;
    } catch (Throwable e) {
        Log.e(LOG_TAG, "Failed to get the IP address", e);
    }
    return null;
}

From source file:com.xperia64.cosi.CosiActivity.java

public String getLocalIpAddress() {
    try {//  w ww. j  a  va2s . 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() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:org.apereo.portal.PortalInfoProviderImpl.java

protected Set<String> getNetworkInterfaceNames() {
    final Enumeration<NetworkInterface> networkInterfacesEnum;
    try {/*from  w  w  w.j  av a2  s  .c  om*/
        networkInterfacesEnum = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.warn("Failed to get list of available NetworkInterfaces.", e);
        return Collections.emptySet();
    }

    final Set<String> names = new LinkedHashSet<String>();
    while (networkInterfacesEnum.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfacesEnum.nextElement();
        names.add(networkInterface.getName());
    }

    return names;
}

From source file:com.nokia.dempsy.messagetransport.tcp.TcpReceiver.java

private static InetAddress getFirstNonLocalhostInetAddress() throws SocketException {
    Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
    while (netInterfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) netInterfaces.nextElement();
        for (Enumeration<InetAddress> loopInetAddress = networkInterface.getInetAddresses(); loopInetAddress
                .hasMoreElements();) {/*from  www.  j a  v a2 s.c o  m*/
            InetAddress tempInetAddress = loopInetAddress.nextElement();
            if (!tempInetAddress.isLoopbackAddress() && tempInetAddress instanceof Inet4Address)
                return tempInetAddress;
        }
    }
    return null;
}

From source file:com.example.android.toyvpn.ToyVpnService.java

public String getLocalIpAddress() {
    String ipv4;/*from   ww w. j av  a 2 s .c  om*/
    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();
                // System.out.println("ip1--:" + inetAddress);
                // System.out.println("ip2--:" + inetAddress.getHostAddress());

                // for getting IPV4 format
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    //  System.out.println("ip---::" + ip);
                    // return inetAddress.getHostAddress().toString();
                    return ipv4;
                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

From source file:weinre.server.ServerSettings.java

public String[] getBoundHosts() {
    if (getBoundHostValue() != null) {
        return new String[] { getBoundHost() };
    }//from   w w  w  .  ja  v  a 2s .  c  om

    ArrayList<String> hosts = new ArrayList<String>();
    List<NetworkInterface> networkInterfaces;
    try {
        networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    } catch (SocketException e) {
        return new String[] { "localhost" };
    }

    for (NetworkInterface networkInterface : networkInterfaces) {
        List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());

        for (InetAddress inetAddress : inetAddresses) {
            hosts.add(inetAddress.getHostName());
        }
    }

    return hosts.toArray(new String[] {});
}

From source file:com.flexive.shared.stream.FxStreamUtils.java

/**
 * Probe all network interfaces and return the most suited to run a StreamServer on.
 * Preferred are interfaces that are not site local.
 *
 * @return best suited host to run a StreamServer
 * @throws UnknownHostException on errors
 */// w  ww. j a  v a2s  .  com
public static InetAddress probeNetworkInterfaces() throws UnknownHostException {
    try {
        final String forcedAddress = System.getProperty("FxStreamIP");
        if (forcedAddress != null) {
            try {
                InetAddress ad = InetAddress.getByName(forcedAddress);
                LOG.info("Binding [fleXive] streamserver to forced address [" + forcedAddress + "] ...");
                return ad;
            } catch (UnknownHostException e) {
                LOG.error("Forced [fleXive] streamserver bind address [" + forcedAddress + "] can not be used: "
                        + e.getMessage() + " - probing available network interfaces ...");
            }
        }
        Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
        NetworkInterface nif;
        InetAddress preferred = null, fallback = null;
        while (nifs.hasMoreElements()) {
            nif = nifs.nextElement();
            if (LOG.isDebugEnabled())
                LOG.debug("Probing " + nif.getDisplayName() + " ...");
            if (nif.getDisplayName().startsWith("vmnet") || nif.getDisplayName().startsWith("vnet"))
                continue;
            Enumeration<InetAddress> inas = nif.getInetAddresses();
            while (inas.hasMoreElements()) {
                InetAddress na = inas.nextElement();
                if (LOG.isDebugEnabled())
                    LOG.debug("Probing " + nif.getDisplayName() + na);
                if (!(na instanceof Inet4Address))
                    continue;
                if (!na.isLoopbackAddress() && na.isReachable(1000)) {
                    if (preferred == null || (preferred.isSiteLocalAddress() && !na.isSiteLocalAddress()))
                        preferred = na;
                }
                if (fallback == null && na.isLoopbackAddress())
                    fallback = na;
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("preferred: " + preferred + " fallback: " + fallback);
        if (preferred != null)
            return preferred;
        if (fallback != null)
            return fallback;
        return InetAddress.getLocalHost();
    } catch (Exception e) {
        return InetAddress.getLocalHost();
    }
}