Example usage for java.net NetworkInterface getName

List of usage examples for java.net NetworkInterface getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get the name of this network interface.

Usage

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *//*  w  w  w  . j  a  va  2  s . c om*/
private final boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    config.setUnsafeBooleanParameter("Enforce Bind IP", true);
    config.setUnsafeBooleanParameter("Check Bind IP On Start", true);
    config.setUnsafeBooleanParameter("Plugin.UPnP.upnp.enable", false);
    config.setUnsafeBooleanParameter("Plugin.UPnP.natpmp.enable", false);

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/

    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "vpnhelper.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("VPNHelper BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "vpnhelper.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);

        addReply(sReply, CHAR_GOOD, "vpnhelper.change.binding",
                new String[] { "" + newConfigBindIP, networkInterface == null ? "null"
                        : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) {

    int newStatusID = STATUS_ID_OK;

    InetAddress newBindIP = null;
    NetworkInterface newBindNetworkInterface = null;

    String s;//  w  w  w  .j  a va 2  s .  c o  m

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "airvpn.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "airvpn.vuze.loopback");
    }

    try {
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress)) {
                newBindIP = bindableAddress;
                newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);

                addReply(sReply, CHAR_GOOD, "airvpn.found.bindable.vpn", new String[] { "" + newBindIP });

                break;
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        boolean foundNIF = false;
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address)) {
                        s = texts.getLocalisedMessageText("airvpn.possible.vpn",
                                new String[] { "" + address, networkAdminInterface.getName() + " ("
                                        + networkAdminInterface.getDisplayName() + ")" });

                        if (newBindIP == null) {
                            foundNIF = true;
                            newBindIP = address;

                            // Either one should work
                            //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);
                            newBindNetworkInterface = NetworkInterface
                                    .getByName(networkAdminInterface.getName());

                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.not.same.address");
                        }

                        addLiteralReply(sReply, s);

                        if (rebindNetworkInterface) {
                            // stops message below from being added, we'll rebind later
                            foundNIF = true;
                        }

                    }
                }
            }
        }

        if (!foundNIF) {
            addReply(sReply, CHAR_BAD, "airvpn.interface.not.found");
        }

        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows, but on Mac returns a wildcard address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("airvpn.nonvuze.probable.route",
                    new String[] { "" + localAddress, networkInterface == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (newBindIP == null) {
                    newBindIP = localAddress;
                    newBindNetworkInterface = networkInterface;

                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " "
                            + texts.getLocalisedMessageText("airvpn.not.same.future.address") + " "
                            + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " "
                            + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);

            } else {
                s = CHAR_WARN + " " + s;
                if (!bindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBindIP == null && foundNIF) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "airvpn.nat.error", new String[] { e.toString() });
    }

    if (newBindIP == null) {
        addReply(sReply, CHAR_BAD, "airvpn.vpn.ip.detect.fail");
        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply);
    return newStatusID;
}

From source file:org.springframework.vault.authentication.MacAddressUserId.java

@Override
public String createUserId() {

    try {/* w w  w.j a  v a  2  s  .co m*/

        NetworkInterface networkInterface = null;
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (StringUtils.hasText(networkInterfaceHint)) {

            try {
                networkInterface = getNetworkInterface(Integer.parseInt(networkInterfaceHint), interfaces);
            } catch (NumberFormatException e) {
                networkInterface = getNetworkInterface((networkInterfaceHint), interfaces);
            }
        }

        if (networkInterface == null) {

            if (StringUtils.hasText(networkInterfaceHint)) {
                log.warn(String.format("Did not find a NetworkInterface applying hint %s",
                        networkInterfaceHint));
            }

            InetAddress localHost = InetAddress.getLocalHost();
            networkInterface = NetworkInterface.getByInetAddress(localHost);

            if (networkInterface == null) {
                throw new IllegalStateException(
                        String.format("Cannot determine NetworkInterface for %s", localHost));
            }
        }

        byte[] mac = networkInterface.getHardwareAddress();
        if (mac == null) {
            throw new IllegalStateException(
                    String.format("Network interface %s has no hardware address", networkInterface.getName()));
        }

        return Sha256.toSha256(Sha256.toHexString(mac));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.rifidi.utilities.device.DeviceAddressManager.java

/**
 * This method enumerates all existing devices in the system.
 *//*from  w  ww. j av a2s .  c  o m*/
@SuppressWarnings("unchecked")
private void enumerateSystemDevices() {
    /* This is the set which will eventually become the new device set */
    Set<SystemDevice> enumeratedDevices = new TreeSet<SystemDevice>();

    /* Grab the previous devices and put them in an easy to use list form */
    List<SystemDevice> previouslyEnumeratedDevices = new ArrayList<SystemDevice>(this.systemDevices);

    /* Enumerate serial devices */
    if (this.serialEnabled) {
        Enumeration commPorts = CommPortIdentifier.getPortIdentifiers();
        while (commPorts.hasMoreElements()) {
            CommPortIdentifier curCommPort = (CommPortIdentifier) commPorts.nextElement();
            if (curCommPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                /* Make a serial port so that we can get baud settings, etc. */
                RXTXPort tempPort = null;

                try {
                    /*
                     * Grab the serial port and get all of its current
                     * settings
                     */
                    tempPort = new RXTXPort(curCommPort.getName());

                    SystemSerialPort portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                            SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING, tempPort.getBaudRate(),
                            tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    /* Check and see if the device already exists */
                    int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(portToAdd);
                    if (existingDeviceIndex != -1) {
                        /* Grab that already existing device */
                        SystemSerialPort existingSerialDevice = (SystemSerialPort) previouslyEnumeratedDevices
                                .get(existingDeviceIndex);

                        /* Copy the creation state over */
                        portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                                existingSerialDevice.getDeviceExistenceType(), tempPort.getBaudRate(),
                                tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    }

                    tempPort.close();

                    /* Add to enumerated devices */
                    enumeratedDevices.add(portToAdd);

                } catch (PortInUseException e) {
                    logger.info(e.getMessage() + " (" + curCommPort.getName() + ")");

                }

            }

        }

    }

    /* Enumerate IP devices and all addresses. */
    /* Get all of the interfaces in the system and print them. */
    Enumeration<NetworkInterface> netInterfaces = null;

    try {
        netInterfaces = NetworkInterface.getNetworkInterfaces();

    } catch (SocketException e) {
        logger.warn(e.getMessage());

    }

    /* Check to see if we have interfaces to add to the device list. */
    if (netInterfaces != null) {
        /* Grab all of the interfaces and their network addresses */
        while (netInterfaces.hasMoreElements()) {
            /* Grab the current interface */
            NetworkInterface curInterface = netInterfaces.nextElement();

            /* Use a tree map for sorted IPs */
            Map<String, SystemNetworkInterface.NetworkAddressType> curInterfaceAddressMap;
            curInterfaceAddressMap = new TreeMap<String, SystemNetworkInterface.NetworkAddressType>();

            /* Get all of the addresses which this interface has */
            Enumeration<InetAddress> curInterfaceAddresses = curInterface.getInetAddresses();

            while (curInterfaceAddresses.hasMoreElements()) {
                /* Append the current address to map */
                InetAddress curAddress = curInterfaceAddresses.nextElement();
                curInterfaceAddressMap.put(curAddress.getHostAddress(),
                        SystemNetworkInterface.NetworkAddressType.PREVIOUSLY_EXISTING);

            }

            /* Create the new device */
            SystemNetworkInterface interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                    curInterface.getName(), SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING,
                    curInterfaceAddressMap);

            /* Check and see if the device already exists */
            int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(interfaceToAdd);
            if (existingDeviceIndex != -1) {
                /* Grab that already existing device */
                SystemNetworkInterface existingNetworkInterface = (SystemNetworkInterface) previouslyEnumeratedDevices
                        .get(existingDeviceIndex);

                /* Copy over the existing device existence type */
                interfaceToAdd = null;
                interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                        curInterface.getName(), existingNetworkInterface.getDeviceExistenceType(),
                        curInterfaceAddressMap);

                /* Copy over the address info */
                Iterator<String> addressIter = interfaceToAdd.getNetworkAddresses().keySet().iterator();
                /* Check each IP and see if it is previously existing */
                while (addressIter.hasNext()) {
                    String curAddress = addressIter.next();
                    SystemNetworkInterface.NetworkAddressType existingType = existingNetworkInterface
                            .getNetworkAddresses().get(curAddress);
                    /* Preserve the existing type */
                    if (existingType != null) {
                        interfaceToAdd.getNetworkAddresses().put(curAddress, existingType);

                    }

                }

            }

            /* Add the new device to the existing devices list */
            enumeratedDevices.add(interfaceToAdd);

        }

    }

    /* Blow out the old system devices */
    this.systemDevices.clear();

    /* Assign the new system devices */
    this.systemDevices = enumeratedDevices;

}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void displaySystemInfo() throws SocketException {

    if (useDevConfig) {
        LOG.warn("Development environment enabled. Do not use this on a production server.");
    }//from ww  w.j  a  v a2s. c o  m

    if (LOG.isInfoEnabled()) {
        LOG.info("Version is " + ContextHolder.getContext().getVersion());
        LOG.info("Java version is " + SystemProperties.get("java.version"));
        LOG.info("Server is installed on " + hostname + "/" + hostAddress);
        LOG.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        LOG.warn("********** WARNING **********");
        LOG.warn("The system has detected that the Java runtime is GNU/GCJ");
        LOG.warn("Adito may not work correctly with this Java runtime");
        LOG.warn("you should reconfigure with a different runtime");
        LOG.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (LOG.isInfoEnabled()) {
            LOG.info("Net interface: " + netface.getName());
        }

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (LOG.isInfoEnabled()) {
                LOG.info("IP address: " + ip.toString());
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("System properties follow:");
    }
    Properties sysProps = System.getProperties();
    for (Map.Entry entry : sysProps.entrySet()) {
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("java.class.path=" + s);
                    }
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    }
                    idx += 256;
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx));
                    }
                    break;
                }
            }
        }
    }
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();//from   w w  w  .  j a  v a2  s.  c  o m

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                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.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Returns the set of broadcast addresses available to the network interfaces of this host. In case of IPv6 the set
 * contains the IPv6 multicast address to reach all nodes on the local link. Moreover, all addresses of the loopback
 * interfaces are added to the set.//from   w  w w  . j a va2s  .c  o  m
 * 
 * @return (possibly empty) set of broadcast addresses reachable by this host
 */
private static Set<InetAddress> getBroadcastAddresses() {

    final Set<InetAddress> broadcastAddresses = new HashSet<InetAddress>();

    // get all network interfaces
    Enumeration<NetworkInterface> ie = null;
    try {
        ie = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOG.error("Could not collect network interfaces of host", e);
        return broadcastAddresses;
    }

    while (ie.hasMoreElements()) {
        NetworkInterface nic = ie.nextElement();
        try {
            if (!nic.isUp()) {
                continue;
            }

            if (nic.isLoopback()) {
                for (InterfaceAddress adr : nic.getInterfaceAddresses()) {
                    broadcastAddresses.add(adr.getAddress());
                }
            } else {

                // check all IPs bound to network interfaces
                for (InterfaceAddress adr : nic.getInterfaceAddresses()) {

                    if (adr == null) {
                        continue;
                    }

                    // collect all broadcast addresses
                    if (USE_IPV6) {
                        try {
                            final InetAddress interfaceAddress = adr.getAddress();
                            if (interfaceAddress instanceof Inet6Address) {
                                final Inet6Address ipv6Address = (Inet6Address) interfaceAddress;
                                final InetAddress multicastAddress = InetAddress.getByName(IPV6MULTICASTADDRESS
                                        + "%" + Integer.toString(ipv6Address.getScopeId()));
                                broadcastAddresses.add(multicastAddress);
                            }

                        } catch (UnknownHostException e) {
                            LOG.error(e);
                        }
                    } else {
                        final InetAddress broadcast = adr.getBroadcast();
                        if (broadcast != null) {
                            broadcastAddresses.add(broadcast);
                        }
                    }
                }
            }

        } catch (SocketException e) {
            LOG.error("Socket exception when checking " + nic.getName() + ". " + "Ignoring this device.", e);
        }
    }

    return broadcastAddresses;
}

From source file:com.adito.server.Main.java

private void displaySystemInfo() throws SocketException {

    ////w  w  w . j  a v  a2s.  c o  m

    if (useDevConfig) {
        log.warn("Development environment enabled. Do not use this on a production server.");
    }

    if (log.isInfoEnabled()) {
        log.info("Version is " + ContextHolder.getContext().getVersion());
        log.info("Java version is " + SystemProperties.get("java.version"));
        log.info("Server is installed on " + hostname + "/" + hostAddress);
        log.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        log.warn("********** WARNING **********");
        log.warn("The system has detected that the Java runtime is GNU/GCJ");
        log.warn("Adito may not work correctly with this Java runtime");
        log.warn("you should reconfigure with a different runtime");
        log.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (log.isInfoEnabled())
            log.info("Net interface: " + netface.getName());

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (log.isInfoEnabled())
                log.info("IP address: " + ip.toString());
        }
    }

    if (log.isInfoEnabled())
        log.info("System properties follow:");
    Properties sysProps = System.getProperties();
    for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (log.isInfoEnabled())
                        log.info("java.class.path=" + s);
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    idx += 256;
                } else {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx));
                    break;
                }
            }
        }
    }
}

From source file:com.sslexplorer.server.Main.java

private void displaySystemInfo() throws SocketException {

    ////from  www .  j av  a 2 s.  c om

    if (useDevConfig) {
        log.warn("Development environment enabled. Do not use this on a production server.");
    }

    if (log.isInfoEnabled()) {
        log.info("Version is " + ContextHolder.getContext().getVersion());
        log.info("Java version is " + SystemProperties.get("java.version"));
        log.info("Server is installed on " + hostname + "/" + hostAddress);
        log.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("SSL-Explorer does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        log.warn("********** WARNING **********");
        log.warn("The system has detected that the Java runtime is GNU/GCJ");
        log.warn("SSL-Explorer may not work correctly with this Java runtime");
        log.warn("you should reconfigure with a different runtime");
        log.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (log.isInfoEnabled())
            log.info("Net interface: " + netface.getName());

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (log.isInfoEnabled())
                log.info("IP address: " + ip.toString());
        }
    }

    if (log.isInfoEnabled())
        log.info("System properties follow:");
    Properties sysProps = System.getProperties();
    for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (log.isInfoEnabled())
                        log.info("java.class.path=" + s);
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    idx += 256;
                } else {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx));
                    break;
                }
            }
        }
    }
}

From source file:com.redhat.rhn.domain.server.Server.java

/**
 * Get the NetworkInteface with the given name (i.e. eth0)
 * @param ifName the interface name (i.e. eth0)
 * @return the NetworkInterface, otherwise null
 */// w w w  .java2 s. com
public NetworkInterface getNetworkInterface(String ifName) {
    for (NetworkInterface nic : getNetworkInterfaces()) {
        if (nic.getName().equals(ifName)) {
            return nic;
        }
    }
    return null;
}