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:org.tellervo.desktop.wsi.WSIServerDetails.java

/**
 * Ping the server to update status//from   w  ww. ja v a 2s  . c  o 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.orangelabs.rcs.platform.network.AndroidNetworkFactory.java

/**
 * Returns the local IP address of a given network interface
 * // w w w .j  av  a2 s.  com
 * @param dnsEntry remote address to find an according local socket address
  * @param type the type of the network interface, should be either
  *        {@link android.net.ConnectivityManager#TYPE_WIFI} or {@link android.net.ConnectivityManager#TYPE_MOBILE}
 * @return Address
 */
// Changed by Deutsche Telekom
public String getLocalIpAddress(DnsResolvedFields dnsEntry, int type) {
    String ipAddress = null;
    try {
        // What kind of remote address (P-CSCF) are we trying to reach?
        boolean isIpv4 = InetAddressUtils.isIPv4Address(dnsEntry.ipAddress);

        // check all available interfaces
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); (en != null)
                && en.hasMoreElements();) {
            NetworkInterface netIntf = (NetworkInterface) en.nextElement();
            for (Enumeration<InetAddress> addr = netIntf.getInetAddresses(); addr.hasMoreElements();) {
                InetAddress inetAddress = addr.nextElement();
                ipAddress = IpAddressUtils.extractHostAddress(inetAddress.getHostAddress());
                // if IP address version doesn't match to remote address
                // version then skip
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && (InetAddressUtils.isIPv4Address(ipAddress) == isIpv4)) {
                    String intfName = netIntf.getDisplayName().toLowerCase();
                    // some devices do list several interfaces though only
                    // one is active
                    if (((type == ConnectivityManager.TYPE_WIFI) && intfName.startsWith("wlan"))
                            || ((type == ConnectivityManager.TYPE_MOBILE) && !intfName.startsWith("wlan"))) {
                        return ipAddress;
                    }
                }
            }
        }
    } catch (Exception e) {
        if (logger.isActivated()) {
            logger.error("getLocalIpAddress failed with ", e);
        }
    }
    return ipAddress;
}

From source file:com.hypersocket.netty.NettyServer.java

protected void bindInterface(Integer port, Set<Channel> channels) throws IOException {

    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

    Set<String> interfacesToBind = new HashSet<String>(
            Arrays.asList(configurationService.getValues("listening.interfaces")));

    if (interfacesToBind.isEmpty()) {

        if (log.isInfoEnabled()) {
            log.info("Binding server to all interfaces on port " + port);
        }/*from   ww w.ja va 2s. com*/
        Channel ch = serverBootstrap.bind(new InetSocketAddress(port));
        channels.add(ch);

        if (log.isInfoEnabled()) {
            log.info("Bound to port " + ((InetSocketAddress) ch.getLocalAddress()).getPort());
        }
    } else {
        while (e.hasMoreElements()) {

            NetworkInterface i = e.nextElement();

            Enumeration<InetAddress> inetAddresses = i.getInetAddresses();

            for (InetAddress inetAddress : Collections.list(inetAddresses)) {

                if (interfacesToBind.contains(inetAddress.getHostAddress())) {
                    try {
                        if (log.isInfoEnabled()) {
                            log.info("Binding server to interface " + i.getDisplayName() + " "
                                    + inetAddress.getHostAddress() + ":" + port);
                        }

                        Channel ch = serverBootstrap.bind(new InetSocketAddress(inetAddress, port));
                        channels.add(ch);

                        if (log.isInfoEnabled()) {
                            log.info("Bound to " + inetAddress.getHostAddress() + ":"
                                    + ((InetSocketAddress) ch.getLocalAddress()).getPort());
                        }

                    } catch (ChannelException ex) {
                        log.error("Failed to bind port", ex);
                    }
                }
            }
        }
    }
}

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

private int handleBound(InetAddress bindIP, StringBuilder sReply) {
    int newStatusID = STATUS_ID_OK;

    String s;//  ww w .j  av a2 s  .co  m
    boolean isGoodExistingBind = matchesVPNIP(bindIP);
    if (isGoodExistingBind) {
        String niName = "Unknown Interface";
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(bindIP);
            niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
        } catch (Throwable e) {
        }
        addReply(sReply, CHAR_GOOD, "pia.bound.good", new String[] { "" + bindIP, niName });
        vpnIP = bindIP;
    } else {
        addReply(sReply, CHAR_BAD, "pia.bound.bad", new String[] { "" + bindIP });
        newStatusID = STATUS_ID_BAD;
    }

    try {
        // 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 (in some cases), 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("pia.nonvuze.probable.route", new String[] { "" + localAddress,
                    networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });
            char replyChar = ' ';

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

                if (localAddress.equals(bindIP)) {
                    replyChar = isGoodExistingBind ? CHAR_GOOD : CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.same.as.vuze");
                } else {
                    // Vuze is bound, default routing goes somewhere else
                    // This is ok, since Vuze will not accept incoming from "somewhere else"
                    // We'll warn, but not update the status id

                    replyChar = CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.not.same");

                    if (isGoodExistingBind) {
                        s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                    }
                }

                addLiteralReply(sReply, replyChar + " " + s);

                if (!isGoodExistingBind && rebindNetworkInterface) {
                    rebindNetworkInterface(networkInterface, localAddress, sReply);
                    // Should we redo test?
                }

            } else {
                // Vuze is bound, default routing goes to somewhere else.
                // Probably network splitting
                replyChar = isGoodExistingBind ? CHAR_WARN : CHAR_BAD;
                if (isGoodExistingBind) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }
                addLiteralReply(sReply, replyChar + " " + s);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return newStatusID;
}

From source file:org.alfresco.filesys.auth.PassthruServerFactory.java

/**
 * Set the broadcast mask to use for NetBIOS name lookups
 * //w ww.  j a  va  2s  .  com
 * @param bcastMask String
 * @exception AlfrescoRuntimeException
 */
public final void setBroadcastMask(String bcastMask) throws IOException {

    if (bcastMask == null || bcastMask.length() == 0) {

        // Clear the NetBIOS subnet mask

        NetBIOSSession.setDefaultSubnetMask(null);
        return;
    }

    // Find the network adapter with the matching broadcast mask

    try {
        Enumeration<NetworkInterface> netEnum = NetworkInterface.getNetworkInterfaces();
        NetworkInterface bcastIface = null;

        while (netEnum.hasMoreElements() && bcastIface == null) {

            NetworkInterface ni = netEnum.nextElement();
            for (InterfaceAddress iAddr : ni.getInterfaceAddresses()) {
                InetAddress broadcast = iAddr.getBroadcast();
                if (broadcast != null && broadcast.getHostAddress().equals(bcastMask))
                    bcastIface = ni;
            }
        }

        // DEBUG

        if (logger.isDebugEnabled()) {
            if (bcastIface != null)
                logger.debug("Broadcast mask " + bcastMask + " found on network interface "
                        + bcastIface.getDisplayName() + "/" + bcastIface.getName());
            else
                logger.debug("Failed to find network interface for broadcast mask " + bcastMask);
        }

        // Check if we found a valid network interface for the broadcast mask

        if (bcastIface == null)
            throw new AlfrescoRuntimeException(
                    "Network interface for broadcast mask " + bcastMask + " not found");

        // Set the NetBIOS broadcast mask

        NetBIOSSession.setDefaultSubnetMask(bcastMask);
    } catch (SocketException ex) {
    }
}

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).//from w  w w .  ja v a2s .  c om
 * 
 * @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.vuze.plugin.azVPN_Helper.CheckerCommon.java

private final int handleFindBindingAddress(InetAddress currentBindIP, StringBuilder sReply, int numLoops) {
    if (currentBindIP == null) {
        addReply(sReply, CHAR_BAD, "!Bind IP null!", new String[] { "" + currentBindIP });
        return STATUS_ID_BAD;
    }//w w  w.  ja  va2 s . c  om

    int newStatusID = STATUS_ID_OK;

    Map<String, BindableInterface> mapBindableInterfaces = new HashMap<String, BindableInterface>();

    BindableInterface newBind = null;

    String s;

    // The "Any" field is equivalent to 0.0.0.0 in dotted-quad notation, which is unbound.
    // "Loopback" is 127.0.0.1, which is bound when Vuze can't bind to
    // user specified interface (ie. kill switched)
    if (currentBindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "vpnhelper.vuze.unbound");
    } else if (currentBindIP.isLoopbackAddress()) {
        addReply(sReply, CHAR_BAD, "vpnhelper.vuze.loopback");
    } else {
        // bound
        boolean isGoodExistingBind = matchesVPNIP(currentBindIP, null);
        if (isGoodExistingBind) {
            String niName = "Unknown Interface";
            try {
                NetworkInterface networkInterface = NetUtils.getByInetAddress(currentBindIP);
                niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
            } catch (Throwable e) {
            }
            addReply(sReply, CHAR_GOOD, "vpnhelper.bound.good", new String[] { "" + currentBindIP, niName });
            vpnIP = currentBindIP;
        } else {
            addReply(sReply, CHAR_BAD, "vpnhelper.bound.bad", new String[] { "" + currentBindIP });
        }
    }

    try {
        boolean foundExistingVPNIP = false;
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

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

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress, null)) {
                String hostAddress = bindableAddress.getHostAddress();
                BindableInterface bi = mapBindableInterfaces.get(hostAddress);
                if (bi == null) {
                    bi = new BindableInterface(bindableAddress, NetUtils.getByInetAddress(bindableAddress));
                    mapBindableInterfaces.put(hostAddress, bi);
                    if (!foundExistingVPNIP && bindableAddress.equals(vpnIP)) {
                        foundExistingVPNIP = true;
                    }
                }
            }
        }

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

        /* Test reverse *
        for (int i = 0; i < interfaces.length / 2; i++) {
           NetworkAdminNetworkInterface temp = interfaces[i];
           interfaces[i] = interfaces[interfaces.length - i - 1];
           interfaces[interfaces.length - i - 1] = temp;
        }
        /**/
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address, null)) {
                        String hostAddress = address.getHostAddress();
                        BindableInterface bi = mapBindableInterfaces.get(hostAddress);
                        if (bi == null) {
                            bi = new BindableInterface(address,
                                    NetUtils.getByName(networkAdminInterface.getName()));
                            mapBindableInterfaces.put(hostAddress, bi);
                            if (!foundExistingVPNIP && address.equals(vpnIP)) {
                                foundExistingVPNIP = true;
                            }
                        }
                    }
                }
            }
        }

        if (vpnIP != null && !foundExistingVPNIP) {
            String niName = "Unknown Interface";
            try {
                NetworkInterface networkInterface = NetUtils.getByInetAddress(currentBindIP);
                niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
            } catch (Throwable e) {
            }
            addReply(sReply, CHAR_WARN, "vpnhelper.existing.not.found",
                    new String[] { "" + currentBindIP, niName });

            if (numLoops == 0) {
                try {
                    Field fldLastNICheck = NetUtils.class.getDeclaredField("last_ni_check");
                    fldLastNICheck.setAccessible(true);
                    fldLastNICheck.set(null, Long.valueOf(-1));
                    return handleFindBindingAddress(currentBindIP, sReply, ++numLoops);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }

        BindableInterface[] array = mapBindableInterfaces.values().toArray(new BindableInterface[0]);
        Arrays.sort(array);

        for (BindableInterface bi : array) {
            if (!bi.isValidPrefixLength(minSubnetMaskBitCount)) {
                addReply(sReply, CHAR_WARN, "vpnhelper.submask.too.broad",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")",
                                "" + bi.networkPrefixLength, "" + minSubnetMaskBitCount });
            } else if (bi.canReach) {
                addReply(sReply, CHAR_GOOD, "vpnhelper.found.bindable.vpn",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")" });
            } else {
                addReply(sReply, CHAR_WARN, "vpnhelper.not.reachable",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")" });
            }
            PluginVPNHelper.log("subnet: " + bi.networkPrefixLength + "; Score: " + bi.score);
        }
        newBind = array.length > 0 && array[0].canReach && array[0].isValidPrefixLength(minSubnetMaskBitCount)
                ? array[0]
                : null;

        InetAddress localAddress = null;

        // 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();
        try {
            socket.connect(testSocketAddress, 0);
            localAddress = socket.getLocalAddress();
        } finally {
            socket.close();
        }

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

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

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

                if (newBind == null) {

                    int networkPrefixLength = getNetworkPrefixLength(networkInterface, localAddress);
                    if (networkPrefixLength >= 0 && networkPrefixLength < minSubnetMaskBitCount) {
                        s = null;
                        addReply(sReply, CHAR_WARN, "vpnhelper.nonvuze.submask.too.broad",
                                new String[] { "" + localAddress,
                                        networkInterface == null ? "null"
                                                : networkInterface.getName() + " ("
                                                        + networkInterface.getDisplayName() + ")",
                                        "" + networkPrefixLength, "" + minSubnetMaskBitCount });
                    } else if (!canReach(localAddress)) {
                        addReply(sReply, CHAR_WARN, "vpnhelper.not.reachable",
                                new String[] { "" + localAddress,
                                        networkInterface == null ? "null"
                                                : networkInterface.getName() + " ("
                                                        + networkInterface.getDisplayName() + ")" });
                    } else {
                        newBind = new BindableInterface(localAddress, networkInterface);

                        s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("vpnhelper.assuming.vpn");
                    }
                } else if (localAddress.equals(newBind.address)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("vpnhelper.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("vpnhelper.not.same.future.address") + " "
                            + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " "
                            + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                if (s != null) {
                    addLiteralReply(sReply, s);
                }

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

                if (newBind == null) {
                    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, "vpnhelper.nat.error", new String[] { e.toString() });
    }

    if (newBind == null) {
        addReply(sReply, CHAR_BAD, "vpnhelper.vpn.ip.detect.fail");

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

        if (configBindIP != null && configBindIP.length() > 0) {
            addReply(sReply, CHAR_WARN,
                    "vpnhelper" + (currentBindIP.isLoopbackAddress() ? ".existing.bind.kept.loopback"
                            : ".existing.bind.kept"),
                    new String[] { configBindIP });

            if (currentBindIP.isLoopbackAddress()) {
                if (numLoops == 0) {
                    try {
                        Field fldLastNICheck = NetUtils.class.getDeclaredField("last_ni_check");
                        fldLastNICheck.setAccessible(true);
                        fldLastNICheck.set(null, Long.valueOf(-1));
                        return handleFindBindingAddress(currentBindIP, sReply, ++numLoops);
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            }
        }

        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBind.networkInterface, newBind.address, sReply);
    return newStatusID;
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

private void printNetworkInterfaces() {
    try {/*ww  w .  j a  v a2  s.c o  m*/
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface ni : Collections.list(nis)) {
            Enumeration<InetAddress> iis = ni.getInetAddresses();
            for (InetAddress ia : Collections.list(iis)) {
                consoleBuffer.append(formatJettyInfoLine("Network interface: %s: %s", ni.getDisplayName(),
                        ia.getHostAddress()));
            }
        }
    } catch (SocketException e) {
        Log.w(TAG, e);
    }
}

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

private int handleBound(InetAddress bindIP, StringBuilder sReply) {
    int newStatusID = STATUS_ID_OK;

    String s;/*from  w  w  w . j ava 2 s . co  m*/
    boolean isGoodExistingBind = matchesVPNIP(bindIP);
    if (isGoodExistingBind) {
        String niName = "Unknown Interface";
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(bindIP);
            niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
        } catch (Throwable e) {
        }
        addReply(sReply, CHAR_GOOD, "airvpn.bound.good", new String[] { "" + bindIP, niName });
        vpnIP = bindIP;
    } else {
        addReply(sReply, CHAR_BAD, "airvpn.bound.bad", new String[] { "" + bindIP });
        newStatusID = STATUS_ID_BAD;
    }

    try {
        // 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 (in some cases), 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.getName() + " (" + networkInterface.getDisplayName() + ")" });
            char replyChar = ' ';

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

                if (localAddress.equals(bindIP)) {
                    replyChar = isGoodExistingBind ? CHAR_GOOD : CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("airvpn.same.as.vuze");
                } else {
                    // Vuze is bound, default routing goes somewhere else
                    // This is ok, since Vuze will not accept incoming from "somewhere else"
                    // We'll warn, but not update the status id

                    replyChar = CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("airvpn.not.same");

                    if (isGoodExistingBind) {
                        s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                    }
                }

                addLiteralReply(sReply, replyChar + " " + s);

                if (!isGoodExistingBind && rebindNetworkInterface) {
                    rebindNetworkInterface(networkInterface, localAddress, sReply);
                    // Should we redo test?
                }

            } else {
                // Vuze is bound, default routing goes to somewhere else.
                // Probably network splitting
                replyChar = isGoodExistingBind ? CHAR_WARN : CHAR_BAD;
                if (isGoodExistingBind) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }
                addLiteralReply(sReply, replyChar + " " + s);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return newStatusID;
}

From source file:com.vuze.plugin.azVPN_PIA.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  av  a  2  s. c o m*/

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "pia.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "pia.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, "pia.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("pia.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("pia.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("pia.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("pia.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, "pia.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("pia.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("pia.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("pia.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("pia.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, "pia.nat.error", new String[] { e.toString() });
    }

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

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