Example usage for java.net NetworkInterface isUp

List of usage examples for java.net NetworkInterface isUp

Introduction

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

Prototype


public boolean isUp() throws SocketException 

Source Link

Document

Returns whether a network interface is up and running.

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 w  w  .  ja  va2  s .c o  m
        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.kei.android.phone.netcap.OutputFragment.java

@Override
public void onClick(final View v) {
    if (v.equals(refreshBT)) {
        adapter.clear();/*from ww  w .  j  a v a2 s . c  o m*/
        try {
            final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            if (interfaces != null && interfaces.size() != 0)
                adapter.add(getResources().getText(R.string.any).toString());
            for (final NetworkInterface ni : interfaces)
                if (ni.isUp())
                    adapter.add(ni.getName());
        } catch (final Throwable e) {
            logException(e);
        }
    } else if (v.equals(browseOutputCaptureTV)) {
        final Map<String, String> extra = new HashMap<String, String>();
        extra.put(FileChooser.FILECHOOSER_TYPE_KEY, "" + FileChooser.FILECHOOSER_TYPE_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_TITLE_KEY, "Save");
        extra.put(FileChooser.FILECHOOSER_MESSAGE_KEY, "Use this folder:? ");
        extra.put(FileChooser.FILECHOOSER_DEFAULT_DIR, browseOutputCaptureTV.getText().toString());
        extra.put(FileChooser.FILECHOOSER_SHOW_KEY, "" + FileChooser.FILECHOOSER_SHOW_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_USER_MESSAGE, getClass().getSimpleName());
        Tools.switchToForResult(owner, FileChooserActivity.class, extra,
                FileChooserActivity.FILECHOOSER_SELECTION_TYPE_DIRECTORY);

    } else if (v.equals(captureBT)) {
        if (!captureBT.isChecked()) {
            captureBT.setChecked(true);
            delete();
        } else {
            String sdest = browseOutputCaptureTV.getText().toString();
            if (sdest.isEmpty()) {
                Tools.showAlertDialog(owner, "Error", "Empty destination folder!");
                captureBT.setChecked(false);
                return;
            }

            File legacy = new File(sdest.replaceFirst("emulated/([0-9]+)/", "emulated/legacy/"));
            File fdest = new File(sdest);
            Log.i(getClass().getSimpleName(), "Test directory '" + legacy + "'");
            if (legacy.isDirectory())
                fdest = legacy;
            if (!fdest.isDirectory()) {
                Tools.showAlertDialog(owner, "Error", "The destination folder is not a valid directory!");
                captureBT.setChecked(false);
                return;
            } else if (!fdest.canWrite()) {
                Tools.showAlertDialog(owner, "Error", "Unable to write into the destination folder!");
                captureBT.setChecked(false);
                return;
            }

            if (!RootTools.isAccessGiven()) {
                Resources r = getResources();
                Tools.toast(owner, R.drawable.ic_launcher, r.getString(R.string.root_toast_error));
                showResult.setText(" " + r.getString(R.string.root_error));
                captureBT.setChecked(false);
                return;
            }

            final PackageManager m = owner.getPackageManager();
            String s = owner.getPackageName();
            try {
                final PackageInfo p = m.getPackageInfo(s, 0);
                s = p.applicationInfo.dataDir;
            } catch (final PackageManager.NameNotFoundException e) {
            }
            s = s + "/netcap";
            copyFile(Build.SUPPORTED_ABIS[0] + "/netcap", s, owner);
            final File netcap = new File(s);
            if (!netcap.exists()) {
                Tools.showAlertDialog(owner, "Error",
                        "'netcap' for '" + Build.SUPPORTED_ABIS[0] + "' was not found!");
                return;
            }
            pname = netcap.getAbsolutePath();
            netcap.setExecutable(true);

            ifaces = "";
            String ni = (String) devicesSp.getSelectedItem();
            if (ni.equals(getResources().getText(R.string.any).toString())) {
                for (int i = 0; i < adapter.getCount(); i++) {
                    ni = adapter.getItem(i);
                    if (ni.equals(getResources().getText(R.string.any).toString()))
                        continue;
                    ifaces += ni;
                    if (i < adapter.getCount() - 1)
                        ifaces += ",";
                }
            } else
                ifaces = ni;

            final File outputFile = new File(fdest,
                    new SimpleDateFormat("yyyyMMdd_hhmmssa'_netcap.pcap'", Locale.US).format(new Date()));
            buffer.clear();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String cmd = netcap.getAbsolutePath() + " -i " + ifaces + " -f "
                                + outputFile.getAbsolutePath() + " -d";
                        if (promiscuousCB.isChecked())
                            cmd += " -p";
                        cmd += " 2>&1";
                        command = new Command(0, cmd) {
                            @Override
                            public void commandOutput(int id, String line) {
                                super.commandOutput(id, line);
                                if (line.startsWith(NETCAP_READY))
                                    pid = line.substring(NETCAP_READY.length());
                                buffer.add(line);
                                owner.runOnUiThread(new Runnable() {
                                    @SuppressWarnings("unchecked")
                                    @Override
                                    public void run() {
                                        final String[] lines = (String[]) buffer.toArray(new String[] {});
                                        final StringBuilder sb = new StringBuilder();
                                        for (final String s : lines)
                                            sb.append(" ").append(s).append("\n");
                                        showResult.setText(sb.toString());
                                    }
                                });
                            }

                            public void commandCompleted(int id, int exitcode) {
                                super.commandCompleted(id, exitcode);
                                owner.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        captureBT.setChecked(false);
                                    }
                                });
                            }

                            public void commandTerminated(int id, String reason) {
                                super.commandTerminated(id, reason);
                            }
                        };
                        RootTools.getShell(true).add(command);
                    } catch (final Exception e) {
                        logException(e);
                    }
                }
            }).start();
        }
    }
}

From source file:net.mm2d.dmsexplorer.ServerListActivity.java

private Collection<NetworkInterface> getWifiInterface() {
    final NetworkInfo ni = mConnectivityManager.getActiveNetworkInfo();
    if (ni == null || !ni.isConnected() || ni.getType() != ConnectivityManager.TYPE_WIFI) {
        return null;
    }// ww  w  . jav  a  2  s.com
    final InetAddress address = getWifiInetAddress();
    if (address == null) {
        return null;
    }
    final Enumeration<NetworkInterface> nis;
    try {
        nis = NetworkInterface.getNetworkInterfaces();
    } catch (final SocketException e) {
        return null;
    }
    while (nis.hasMoreElements()) {
        final NetworkInterface nif = nis.nextElement();
        try {
            if (nif.isLoopback() || nif.isPointToPoint() || nif.isVirtual() || !nif.isUp()) {
                continue;
            }
            final List<InterfaceAddress> ifas = nif.getInterfaceAddresses();
            for (final InterfaceAddress a : ifas) {
                if (a.getAddress().equals(address)) {
                    final Collection<NetworkInterface> c = new ArrayList<>();
                    c.add(nif);
                    return c;
                }
            }
        } catch (final SocketException ignored) {
        }
    }
    return null;
}

From source file:org.sltpaya.tool.Utils.java

/**
 * ?APN?/*from w w w  . j  a v  a  2s. c  om*/
 * @return ?
 */
private boolean getApnStatus() {
    Matcher matcher;
    String name;
    try {
        Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
        if (niList != null) {
            for (NetworkInterface intf : Collections.list(niList)) {
                if (!intf.isUp() || intf.getInterfaceAddresses().size() == 0) {
                    continue;
                }
                Log.d(TAG, "isVpnUsed() NetworkInterface Name: " + intf.getName());
                name = intf.getName();
                matcher = Pattern.compile("tun\\d").matcher(name);
                if (matcher.find()) {
                    System.out.println("vpn??????" + matcher.group());
                    return true;
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return false;
}

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

private String getBroadcastIP() {
    String myIP = null;//from  w  ww.  j  a  v  a2 s .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:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

@Override
protected void activate(Map<String, Object> configProperties) {
    super.activate(configProperties);

    broadcastAddresses = new ArrayList<InetSocketAddress>();
    interfaceAddresses = new ArrayList<InetAddress>();

    Enumeration<NetworkInterface> networkInterfaces = null;
    try {/*from  w w w  . j  av a2 s. c o m*/
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }
    if (networkInterfaces != null) {
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface iface = networkInterfaces.nextElement();
            try {
                if (iface.isUp() && !iface.isLoopback()) {
                    for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
                        if (ifaceAddr.getAddress() instanceof Inet4Address) {
                            logger.debug("Adding '{}' as interface address with MTU {}", ifaceAddr.getAddress(),
                                    iface.getMTU());
                            if (iface.getMTU() > bufferSize) {
                                bufferSize = iface.getMTU();
                            }
                            interfaceAddresses.add(ifaceAddr.getAddress());
                            if (ifaceAddr.getBroadcast() != null) {
                                logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast());
                                broadcastAddresses
                                        .add(new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
            }
        }
    }
}

From source file:org.tellervo.desktop.wsi.WSIServerDetails.java

/**
 * Ping the server to update status// www. ja va  2 s.co m
 * 
 * @return
 */
public boolean pingServer() {
    // First make sure we have a network connection
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nic = interfaces.nextElement();
            if (nic.isLoopback())
                continue;

            if (nic.isUp()) {
                log.debug("Network adapter '" + nic.getDisplayName() + "' is up");
                isNetworkConnected = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (!isNetworkConnected) {
        status = WSIServerStatus.NO_CONNECTION;
        errMessage = "You do not appear to have a network connection.\nPlease check you network and try again.";
        return false;
    }

    URI url = null;
    BufferedReader dis = null;
    DefaultHttpClient client = new DefaultHttpClient();

    try {

        String path = App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid-url!");

        url = new URI(path.trim());

        // Check we're accessing HTTP or HTTPS connection
        if (url.getScheme() == null
                || ((!url.getScheme().equals("http")) && !url.getScheme().equals("https"))) {
            errMessage = "The webservice URL is invalid.  It should begin http or https";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        }

        // load cookies
        client.setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore());

        if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) {
            // Using strict security so don't allow self signed certificates for SSL
        } else {
            // Not using strict security so allow self signed certificates for SSL
            if (url.getScheme().equals("https"))
                WebJaxbAccessor.setSelfSignableHTTPSScheme(client);
        }

        HttpGet req = new HttpGet(url);

        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpResponse response = client.execute(req);

        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream responseIS = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS));
            String s = "";
            while ((s = reader.readLine()) != null) {
                if (s.contains("<webserviceVersion>")) {
                    String[] strparts = s.split("<[/]*webserviceVersion>");
                    if (strparts.length > 0)
                        parserThisServerVersion(strparts[1]);

                    status = WSIServerStatus.VALID;
                    return true;
                } else if (s.startsWith("<b>Parse error</b>:")) {
                    status = WSIServerStatus.STATUS_ERROR;
                    errMessage = s.replace("<b>", "").replace("</b>", "").replace("<br />", "");
                    return false;
                }
            }
        } else if (response.getStatusLine().getStatusCode() == 403) {
            String serverType = "";
            try {
                serverType = "(" + response.getHeaders("Server")[0].getValue() + ")";
            } catch (Exception e) {
            }

            errMessage = "The webserver " + serverType
                    + " reports you do not have permission to access this URL.\n"
                    + "This is a problem with the server setup, not your Tellervo username/password.\n"
                    + "Contact your systems administrator for help.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() == 404) {
            errMessage = "Server reports that there is no webservice at this URL.\nPlease check and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.URL_NOT_TELLERVO_WS;
            return false;
        } else if (response.getStatusLine().getStatusCode() == 407) {
            errMessage = "Proxy authentication is required to access this server.\nCheck your proxy server settings and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() >= 500) {
            errMessage = "Internal server error (code " + response.getStatusLine().getStatusCode()
                    + ").\nContact your systems administrator";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() >= 300
                && response.getStatusLine().getStatusCode() < 400) {
            errMessage = "Server reports that your request has been redirected to a different URL.\nCheck your URL and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else {
            errMessage = "The server is returning an error:\nCode: " + response.getStatusLine().getStatusCode()
                    + "\n" + response.getStatusLine().getReasonPhrase();
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        }

    } catch (ClientProtocolException e) {
        errMessage = "There was as problem with the HTTP protocol.\nPlease contact the Tellervo developers.";
        log.debug(errMessage);
        status = WSIServerStatus.STATUS_ERROR;
        return false;
    } catch (SSLPeerUnverifiedException sslex) {
        errMessage = "You have strict security policy enabled but the server you are connecting to does not have a valid SSL certificate.";
        log.debug(errMessage);
        status = WSIServerStatus.SSL_CERTIFICATE_PROBLEM;
        return false;
    } catch (IOException e) {

        if (url.toString().startsWith("http://10.")) {
            // Provide extra help to those failing to access a local server address
            errMessage = "There is no response from the server at this URL. Are you sure this is the correct address?\n\nPlease note that the URL you have specified is a local network address. You will need to be on the same network as the server to gain access.";
        } else if (e.getMessage().contains("hostname in certificate didn't match")) {
            errMessage = "The security certificate for this server is for a different domain.  This could be an indication of a 'man-in-the-middle' attack.";
        } else {
            errMessage = "There is no response from the server at this URL.\nAre you sure this is the correct address and that\nthe server is turned on and configured correctly?";
        }
        log.debug(errMessage);
        log.debug("IOException " + e.getLocalizedMessage());
        status = WSIServerStatus.URL_NOT_RESPONDING;
        return false;
    } catch (URISyntaxException e) {
        errMessage = "The web service URL you entered was malformed.\nPlease check for typos and try again.";
        log.debug(errMessage);
        status = WSIServerStatus.MALFORMED_URL;
        return false;
    } catch (IllegalStateException e) {
        errMessage = "This communications protocol is not supported.\nPlease contact your systems administrator.";
        log.debug(errMessage);
        status = WSIServerStatus.MALFORMED_URL;
        return false;
    } catch (Exception e) {
        errMessage = "The URL you specified exists, but does not appear to be a Tellervo webservice.\nPlease check and try again.";
        log.debug(errMessage);
        status = WSIServerStatus.URL_NOT_TELLERVO_WS;
        return false;
    } finally {
        try {
            if (dis != null) {
                dis.close();
            }
        } catch (IOException e) {
        }
    }

    status = WSIServerStatus.URL_NOT_TELLERVO_WS;

    return false;

}

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)./*w w  w .  j a  v a  2s  .  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:com.cloud.utils.net.NetUtils.java

public static InetAddress[] getAllLocalInetAddresses() {
    final List<InetAddress> addrList = new ArrayList<InetAddress>();
    try {// ww  w.  j av a 2  s . co m
        for (final NetworkInterface ifc : IteratorUtil
                .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual()) {
                for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
                    addrList.add(addr);
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
    }

    final InetAddress[] addrs = new InetAddress[addrList.size()];
    if (addrList.size() > 0) {
        System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
    }
    return addrs;
}