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.apporiented.hermesftp.utils.NetUtils.java

/**
 * Returns the machine's network address.
 * /*from w  w  w .ja va2s.  c  o  m*/
 * @param fallBackToLocalhost True if loopback address should be used if
 *            there is no net.
 * @return The ip address.
 */
public static InetAddress getMachineAddress(boolean fallBackToLocalhost) {
    InetAddress result = null;
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            InetAddress ia = getMachineAddress(ni);
            if (ia != null) {
                result = ia;
                break;
            }
        }
        if (result == null) {
            result = InetAddress.getLocalHost();
        }

    } catch (SocketException e) {
        log.error(e);
    } catch (UnknownHostException e) {
        log.error(e);
    }
    return result;
}

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

/**
 * returns the MAC address of this instance
 * /*from ww  w.  j a v a2s .com*/
 * @return MAC or empty string
 */
public static String getMac() {
    try {
        InetAddress ip = InetAddress.getLocalHost();
        if (ip != null) {
            // we are connected to Internet/router and have an IP
            NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
            if (ni == null) {
                // search for other interfaces
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface network = networkInterfaces.nextElement();
                    if (!network.isLoopback()) {
                        ni = network;
                        break;
                    }
                }
            }
            String macAddress = formatMac(ni.getHardwareAddress());
            if (macAddress != null && !macAddress.isEmpty()) {
                return macAddress;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.warn("Error getting MAC from LocalHost IP - not connected to internet/router?");
    }

    try {
        for (Enumeration<NetworkInterface> nif = NetworkInterface.getNetworkInterfaces(); nif
                .hasMoreElements();) {
            NetworkInterface ni = null;
            try {
                ni = nif.nextElement();
                String macAddress = formatMac(ni.getHardwareAddress());
                if (macAddress != null && !macAddress.isEmpty()) {
                    // get first
                    return macAddress;
                }
            } catch (Exception e2) {
                LOGGER.warn("Error getting MAC of " + ni);
            }
        }
        return UNKNOWN_MAC;
    } catch (Exception e) {
        LOGGER.warn("I/O Error on getting network interfaces");
        return UNKNOWN_MAC;
    }
}

From source file:org.chromium.ChromeSystemNetwork.java

private void getNetworkInterfaces(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/* www .ja  va2  s .c  o m*/
        public void run() {
            try {
                JSONArray ret = new JSONArray();
                ArrayList<NetworkInterface> interfaces = Collections
                        .list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface iface : interfaces) {
                    if (iface.isLoopback()) {
                        continue;
                    }
                    for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) {
                        InetAddress address = interfaceAddress.getAddress();
                        if (address == null) {
                            continue;
                        }
                        JSONObject data = new JSONObject();
                        data.put("name", iface.getDisplayName());
                        // Strip address scope zones for IPv6 address.
                        data.put("address", address.getHostAddress().replaceAll("%.*", ""));
                        data.put("prefixLength", interfaceAddress.getNetworkPrefixLength());

                        ret.put(data);
                    }
                }

                callbackContext.success(ret);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error occured while getting network interfaces", e);
                callbackContext.error("Could not get network interfaces");
            }
        }
    });
}

From source file:adams.core.net.InternetHelper.java

/**
 * Returns the IP address determined from the network interfaces (using
 * the IP address of the one with a proper host name).
 *
 * @return       the IP address/*from   ww  w  .  j  ava2s  . co m*/
 */
public static synchronized String getIPFromNetworkInterface() {
    String result;
    List<String> list;
    Enumeration<NetworkInterface> enmI;
    NetworkInterface intf;
    Enumeration<InetAddress> enmA;
    InetAddress addr;
    boolean found;

    result = null;

    if (m_IPNetworkInterface == null) {
        list = new ArrayList<>();
        found = false;
        try {
            enmI = NetworkInterface.getNetworkInterfaces();
            while (enmI.hasMoreElements()) {
                intf = enmI.nextElement();
                // skip non-active ones
                if (!intf.isUp())
                    continue;
                enmA = intf.getInetAddresses();
                while (enmA.hasMoreElements()) {
                    addr = enmA.nextElement();
                    list.add(addr.getHostAddress());
                    if (addr.getHostName().indexOf(':') == -1) {
                        result = addr.getHostAddress();
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
        } catch (Exception e) {
            // ignored
        }

        if (result == null) {
            if (list.size() > 0)
                result = list.get(0);
            else
                result = "<unknown>";
        }

        m_IPNetworkInterface = result;
    } else {
        result = m_IPNetworkInterface;
    }

    return result;
}

From source file:net.sf.jasperreports.phantomjs.InetUtil.java

public static Inet4Address getIPv4Loopback() {
    InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
    //the phantomjs web server module only works with IPv4
    if (loopbackAddress instanceof Inet4Address) {
        return (Inet4Address) loopbackAddress;
    }/*from   w  w w .j a  v a 2s . com*/

    try {
        InetAddress[] addresses = InetAddress.getAllByName(loopbackAddress.getHostName());
        for (InetAddress inetAddress : addresses) {
            if (inetAddress instanceof Inet4Address) {
                return (Inet4Address) inetAddress;
            }
        }
    } catch (UnknownHostException e) {
        log.warn("Error while determining loopback addresses for " + loopbackAddress.getHostName(), e);
    }

    try {
        //keep looking for a IPv4 loopback address
        for (Enumeration<NetworkInterface> itfs = NetworkInterface.getNetworkInterfaces(); itfs
                .hasMoreElements();) {
            NetworkInterface itf = itfs.nextElement();
            if (itf.isLoopback()) {
                for (Enumeration<InetAddress> addresses = itf.getInetAddresses(); addresses
                        .hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet4Address) {
                        return (Inet4Address) address;
                    }
                }
            }
        }
    } catch (SocketException e) {
        log.warn("Error while listing network interfaces", e);
    }

    return null;
}

From source file:utils.Config.java

/**
 * @return the default IP address// www. ja v  a 2s  .c  om
 * @throws SocketException
 * @throws UnknownHostException
 */
private static InetAddress getDefaultAddress() throws SocketException, UnknownHostException {
    Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
    while (n.hasMoreElements()) {
        Enumeration<InetAddress> a = n.nextElement().getInetAddresses();
        while (a.hasMoreElements()) {
            InetAddress address = a.nextElement();
            if (!address.isAnyLocalAddress() && (address instanceof Inet4Address)) {
                return address;
            }
        }
    }
    return InetAddress.getLocalHost();
}

From source file:com.kevinshen.beyondupnp.util.Utils.java

/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string/* ww w .  j ava2  s .co  m*/
 */
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac == null)
                return "";
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < mac.length; idx++)
                buf.append(String.format("%02X:", mac[idx]));
            if (buf.length() > 0)
                buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:massbank.svn.SVNUtils.java

/**
 * /*from  w w w . j  a  v a2 s  .co m*/
 */
public static String getLocalIPAddress() {
    String address = "";
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface network = interfaces.nextElement();
            Enumeration<InetAddress> addresses = network.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress inet = addresses.nextElement();
                if (!inet.isLoopbackAddress() && inet instanceof Inet4Address) {
                    return inet.getHostAddress();
                }
            }
        }
        address = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
    }
    return address;
}

From source file:eu.eubrazilcc.lvl.core.util.NetworkingUtils.java

/**
 * Gets the first public IP address of the host. If no public address are found, one of the private
 * IPs are randomly selected. Otherwise, it returns {@code localhost}.
 * @return the first public IP address of the host.
 *//*  w  ww  .j a va2s. co  m*/
public static final String getInet4Address() {
    String inet4Address = null;
    final List<String> localAddresses = new ArrayList<String>();
    try {
        final Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        if (networks != null) {
            final List<NetworkInterface> ifs = Collections.list(networks);
            for (int i = 0; i < ifs.size() && inet4Address == null; i++) {
                final Enumeration<InetAddress> inetAddresses = ifs.get(i).getInetAddresses();
                if (inetAddresses != null) {
                    final List<InetAddress> addresses = Collections.list(inetAddresses);
                    for (int j = 0; j < addresses.size() && inet4Address == null; j++) {
                        final InetAddress address = addresses.get(j);
                        if (address instanceof Inet4Address && !address.isAnyLocalAddress()
                                && !address.isLinkLocalAddress() && !address.isLoopbackAddress()
                                && StringUtils.isNotBlank(address.getHostAddress())) {
                            final String hostAddress = address.getHostAddress().trim();
                            if (!hostAddress.startsWith("10.") && !hostAddress.startsWith("172.16.")
                                    && !hostAddress.startsWith("192.168.")) {
                                inet4Address = hostAddress;
                            } else {
                                localAddresses.add(hostAddress);
                            }
                            LOGGER.trace(
                                    "IP found - Name: " + address.getHostName() + ", Addr: " + hostAddress);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Failed to discover public IP address for this host", e);
    }
    return (StringUtils.isNotBlank(inet4Address) ? inet4Address
            : (!localAddresses.isEmpty() ? localAddresses.get(new Random().nextInt(localAddresses.size()))
                    : "localhost")).trim();
}

From source file:com.beetle.framework.util.OtherUtil.java

/**
 * ?ip??char=2/*from ww  w.  j  av  a2  s  . c om*/
 * 
 * @return
 */
public static String getLocalHostIps() {
    StringBuffer sb = new StringBuffer();
    final char flag = 2;
    try {
        Enumeration<?> netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
            Enumeration<InetAddress> ips = ni.getInetAddresses();
            while (ips.hasMoreElements()) {
                InetAddress inetAddress = ips.nextElement();
                String ip = inetAddress.getHostAddress();
                if (!inetAddress.isLoopbackAddress() && ip.indexOf(":") == -1) {
                    sb.append(ip).append(flag);
                }
            }
        }
    } catch (Exception e) {
        return "";
    }
    return sb.toString();
}