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:org.deviceconnect.android.manager.core.util.DConnectUtil.java

/**
 * Gets the ip address.//from   w ww . j a  v  a  2 s.c o m
 *
 * @param context Context of application
 * @return Returns ip address
 */
public static String getIPAddress(final Context context) {
    Context appContext = context.getApplicationContext();
    WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
    ConnectivityManager cManager = (ConnectivityManager) appContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = cManager.getActiveNetworkInfo();
    String en0Ip = null;
    if (network != null) {
        switch (network.getType()) {
        case ConnectivityManager.TYPE_ETHERNET:
            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();
                        if (inetAddress instanceof Inet4Address
                                && !inetAddress.getHostAddress().equals("127.0.0.1")) {
                            en0Ip = inetAddress.getHostAddress();
                            break;
                        }
                    }
                }
            } catch (SocketException e) {
                Log.e("DConnectUtil", "Get Ethernet IP Error", e);
            }
        }
    }

    if (en0Ip != null) {
        return en0Ip;
    } else {
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
        return String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    }
}

From source file:license.ExtraTestWakeLicense.java

/**
 * ?mac?/*from ww  w .ja  va 2 s.com*/
 * @param sb
 * @throws Exception
 */
private static void mac(StringBuilder sb) throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces)) {
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
    }
}

From source file:org.psit.transwatcher.TransWatcher.java

private String getBroadcastIP() {
    String myIP = null;/*w  w  w .j  av a 2s .  c  o m*/

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && myIP == null) {
            NetworkInterface current = interfaces.nextElement();
            notifyMessage(current.toString());
            notifyMessage("Name: " + current.getName());
            if (!current.isUp() || current.isLoopback() || current.isVirtual()
                    || !current.getName().startsWith("wl"))
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress())
                    continue;
                if (current_addr instanceof Inet4Address) {
                    myIP = current_addr.getHostAddress();
                    break;
                }
            }
        }
    } catch (Exception exc) {
        notifyMessage("Error determining network interfaces:\n");
    }

    if (myIP != null) {
        // broadcast for IPv4
        StringTokenizer st = new StringTokenizer(myIP, ".");
        StringBuffer broadcastIP = new StringBuffer();
        // hate that archaic string puzzle
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append("255");
        return broadcastIP.toString();
    }

    return null;
}

From source file:com.oneops.inductor.Config.java

/**
 * Retruns the inductor IP address (IPV4 address). If there are multiple
 * NICs/IfAddresses, it selects the first one. Openstack VMs normally has
 * only one network interface (eth0)./* www  .j av  a2 s  . c  o  m*/
 * 
 * @return IPV4 address of inductor with interface name. Returns
 *         <code>null</code> if it couldn't find anything.
 */
private String getInductorIPv4Addr() {
    try {
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        while (nics.hasMoreElements()) {
            NetworkInterface nic = nics.nextElement();
            if (nic.isUp() && !nic.isLoopback()) {
                Enumeration<InetAddress> addrs = nic.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress add = addrs.nextElement();
                    // Print only IPV4 address
                    if (add instanceof Inet4Address && !add.isLoopbackAddress()) {
                        // Log the first one.
                        String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")";
                        logger.info("Inductor IP : " + ip);
                        return ip;
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Error getting inductor IP address", e);
        // Skip any errors
    }
    return null;
}

From source file:org.chromium.ChromeSocket.java

private void getNetworkList(CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    try {//w w  w .  j  ava  2  s.c  o m
        JSONArray list = new JSONArray();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        NetworkInterface iface;
        // Enumerations are a crappy legacy API, can't use the for (foo : bar) syntax.
        while (interfaces.hasMoreElements()) {
            iface = interfaces.nextElement();
            if (iface.isLoopback()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) {
                InetAddress address = interfaceAddress.getAddress();
                if (address != null) {
                    JSONObject data = new JSONObject();
                    data.put("name", iface.getDisplayName());
                    // Strip percent suffix off of ipv6 addresses to match desktop behaviour.
                    data.put("address", address.getHostAddress().replaceAll("%.*", ""));
                    data.put("prefixLength", interfaceAddress.getNetworkPrefixLength());
                    list.put(data);
                }
            }
        }

        callbackContext.success(list);
    } catch (SocketException se) {
        callbackContext.error("SocketException: " + se);
    }
}

From source file:com.singularityeye.eyetrack.MapsActivity.java

private String getHostAddress() {
    try {//from  w  w  w. j  av  a2s  . c o m
        // iterate over interfaces
        for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces(); networkInterfaces.hasMoreElements();) {
            NetworkInterface nextInterface = networkInterfaces.nextElement();
            // iterate over ip addresses (note: one interface could have more than one ip address)
            for (Enumeration<InetAddress> ipAddresses = nextInterface.getInetAddresses(); ipAddresses
                    .hasMoreElements();) {
                InetAddress nextIpAddress = ipAddresses.nextElement();
                // get an IPv4 address
                if (!nextIpAddress.isLoopbackAddress() && nextIpAddress instanceof Inet4Address) {
                    return nextIpAddress.getHostAddress(); // get first ip address
                }
            }
        }
    } catch (SocketException e) {
        Log.e("ERROR", "GetHostAddressException: " + e.getMessage());
    }
    return null;
}

From source file:com.att.arocollector.AROCollectorActivity.java

/**
 * check a network interface by name/* w  ww  .  ja  va2  s.co m*/
 *
 * @param context
 * @param networkInterfaceName
 * @return true if interface exists and is active
 * @throws Exception
 */
private boolean checkForActiveInterface(Context context, String networkInterfaceName) throws Exception {

    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface intf : interfaces) {
        if (intf.getName().equals(networkInterfaceName)) {
            return intf.isUp();
        }
    }
    return false;
}

From source file:org.basdroid.common.NetworkUtils.java

/**
 * Get IP address from first non-localhost interface
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @param useIPv4  true=return ipv4, false=return ipv6
 * @return  address or empty string//from  w  w w.  j  ava2s . c  o m
 */
public static String getIPAddress(String interfaceName, boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            List<InetAddress> inetAddresses = Collections.list(intf.getInetAddresses());
            for (InetAddress inetAddr : inetAddresses) {
                if (!inetAddr.isLoopbackAddress()) {
                    String address = inetAddr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(address);
                    if (useIPv4) {
                        if (isIPv4) {
                            return address;
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = address.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? address : address.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

@SuppressWarnings("unchecked")
private void addIps(JSONObject values) {
    List<String> ip4s = new ArrayList<>();
    List<String> ip6s = new ArrayList<>();
    String ip = "unknown";
    try {/* w  w  w  .ja  va  2 s. co m*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress address = inetAddresses.nextElement();
                if (address instanceof Inet4Address) {
                    ip4s.add(address.getHostAddress() + "_" + address.getHostName());
                    if (!address.isLinkLocalAddress() && !address.isAnyLocalAddress()
                            && !address.isLoopbackAddress()) {
                        ip = address.getHostAddress();
                    }
                }
                if (address instanceof Inet6Address) {
                    ip6s.add(address.getHostAddress() + "_" + address.getHostName());
                }
            }
        }
        ip4s.add("LOC_" + InetAddress.getLocalHost().getHostAddress() + "_"
                + InetAddress.getLocalHost().getHostName());
        if (!ip4s.isEmpty()) {
            values.put("ip", ip);
            values.put("ip4s", ip4s);
        }
        if (!ip6s.isEmpty()) {
            values.put("ip6s", ip6s);
        }
    } catch (UnknownHostException | SocketException e) {
        values.put("ip", "offline_" + e.getMessage());
    }
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

public static String getMacAddr() {
    try {// w  ww.  ja  v  a  2  s.co m
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0"))
                continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                res1.append(Integer.toHexString(b & 0xFF) + ":");
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception e) {
        throw new NfcTagDroidException("can't get mac address", e);
    }
    return "";
}