Example usage for java.net NetworkInterface getDisplayName

List of usage examples for java.net NetworkInterface getDisplayName

Introduction

In this page you can find the example usage for java.net NetworkInterface getDisplayName.

Prototype

public String getDisplayName() 

Source Link

Document

Get the display name of this network interface.

Usage

From source file:com.phonemetra.account.util.AccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(Account.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {/* www.ja v a 2s  . c o m*/
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (Account.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}

From source file:net.straylightlabs.archivo.controller.TelemetryController.java

private static List<String> getNetworkInterfaces() {
    List<String> nics = new ArrayList<>();
    try {/*from w w w .j  a  v  a  2s  . c  o  m*/
        for (NetworkInterface nic : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (nic.isUp())
                nics.add(String.format(
                        "name='%s' isLoopback=%b isP2P=%b isVirtual=%b multicast=%b addresses=[%s]\n",
                        nic.getDisplayName(), nic.isLoopback(), nic.isPointToPoint(), nic.isVirtual(),
                        nic.supportsMulticast(), getAddressesAsString(nic)));
        }
    } catch (SocketException e) {
        logger.error("Error fetching network interface list: ", e);
    }
    return nics;
}

From source file:org.ngrinder.recorder.util.NetworkUtil.java

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
        throws SocketException {
    Enumeration<?> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        if (!i.isUp()) {
            continue;
        }/*w  w  w.  ja  v a2s  .  c  o  m*/
        if (StringUtils.containsIgnoreCase(i.getDisplayName(), "Host-Only")) {
            continue;
        }
        for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

From source file:ee.ria.xroad.proxy.opmonitoring.OpMonitoringBuffer.java

private static String getIpAddress() {
    try {/*from ww  w. j a  v  a  2s  .c om*/
        if (ipAddress == null) {
            NetworkInterface ni = list(getNetworkInterfaces()).stream()
                    .filter(OpMonitoringBuffer::isNonLoopback).findFirst()
                    .orElseThrow(() -> new Exception(NO_INTERFACE_FOUND));

            Exception addressNotFound = new Exception(NO_ADDRESS_FOUND + ni.getDisplayName());

            ipAddress = list(ni.getInetAddresses()).stream().filter(addr -> !addr.isLinkLocalAddress())
                    .findFirst().orElseThrow(() -> addressNotFound).getHostAddress();

            if (ipAddress == null) {
                throw addressNotFound;
            }
        }

        return ipAddress;
    } catch (Exception e) {
        log.error("Cannot get IP address of a non-loopback network interface", e);

        return "0.0.0.0";
    }
}

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 a2s  .  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:com.adamkruger.myipaddressinfo.NetworkInfoFragment.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private static List<NetworkInterfaceInfo> getNetworkInterfaceInfos() {
    List<NetworkInterfaceInfo> networkInterfaceInfos = new ArrayList<NetworkInterfaceInfo>();
    try {//from  w w w.jav a2s  .c o  m
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface networkInterface : interfaces) {
            NetworkInterfaceInfo networkInterfaceInfo = new NetworkInterfaceInfo();
            networkInterfaceInfo.name = networkInterface.getDisplayName();
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
                byte[] MAC = networkInterface.getHardwareAddress();
                if (MAC != null) {
                    StringBuilder stringBuilder = new StringBuilder(18);
                    for (byte b : MAC) {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append(':');
                        }
                        stringBuilder.append(String.format("%02x", b));
                    }
                    networkInterfaceInfo.MAC = stringBuilder.toString();
                }

                networkInterfaceInfo.MTU = networkInterface.getMTU();
            }
            List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses());
            for (InetAddress address : addresses) {
                if (!address.isLoopbackAddress()) {
                    networkInterfaceInfo.ipAddresses.add(InetAddressToString(address));
                }
            }
            if (networkInterfaceInfo.ipAddresses.size() > 0) {
                networkInterfaceInfos.add(networkInterfaceInfo);
            }
        }
    } catch (SocketException e) {
    }

    return networkInterfaceInfos;
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Returns the last adapter it finds that is not a loopback
 *
 * @return Adapter to use/*from  w  w w  .  java 2  s.  c  om*/
 */
public static List<NetworkInterface> getNetworkAdapters() {
    List<NetworkInterface> returnValue = new ArrayList<NetworkInterface>();
    try {

        // Loop round all the adapters

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

            // Get the MAC address if it exists

            NetworkInterface network = networkInterfaces.nextElement();
            byte[] mac = network.getHardwareAddress();
            if (mac != null && mac.length > 0 && network.getInterfaceAddresses() != null) {
                returnValue.add(network);
                logger.debug("Current MAC address : {} ({})", returnValue, network.getDisplayName());
            }
        }
    } catch (Exception e) {
        logger.error("Cannot determine the local MAC address - {}", e.getMessage());
    }
    return returnValue;
}

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
 *//*  ww  w .j  av a2 s. 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();
    }
}

From source file:Main.java

public static NetworkInterface getActiveNetworkInterface() {

    Enumeration<NetworkInterface> interfaces = null;
    try {//from  www  . j  av a2s. c om
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }

    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();

        /* Check if we have a non-local address. If so, this is the active
         * interface.
         *
         * This isn't a perfect heuristic: I have devices which this will
         * still detect the wrong interface on, but it will handle the
         * common cases of wifi-only and Ethernet-only.
         */
        if (iface.getName().startsWith("w")) {
            //this is a perfect hack for getting wifi alone

            while (inetAddresses.hasMoreElements()) {
                InetAddress addr = inetAddresses.nextElement();

                if (!(addr.isLoopbackAddress() || addr.isLinkLocalAddress())) {
                    Log.d("LSSDP", "DisplayName" + iface.getDisplayName() + " Name " + iface.getName());

                    return iface;
                }
            }
        }
    }

    return null;
}

From source file:net.ftb.util.OSUtils.java

/**
 * Grabs the mac address of computer and makes it 10 times longer
 * @return a byte array containing mac address
 *//* w w w .  ja  v  a2  s .  co  m*/
public static byte[] getMacAddress() {
    if (cachedMacAddress != null && cachedMacAddress.length >= 10) {
        return cachedMacAddress;
    }
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface network = networkInterfaces.nextElement();
            byte[] mac = network.getHardwareAddress();
            if (mac != null && mac.length > 0 && !network.isLoopback() && !network.isVirtual()
                    && !network.isPointToPoint() && network.getName().substring(0, 3) != "ham") {
                Logger.logDebug("Interface: " + network.getDisplayName() + " : " + network.getName());
                cachedMacAddress = new byte[mac.length * 10];
                for (int i = 0; i < cachedMacAddress.length; i++) {
                    cachedMacAddress[i] = mac[i - (Math.round(i / mac.length) * mac.length)];
                }
                return cachedMacAddress;
            }
        }
    } catch (SocketException e) {
        Logger.logWarn("Exception getting MAC address", e);
    }

    Logger.logWarn("Failed to get MAC address, using default logindata key");
    return new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
}