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:org.graphwalker.Util.java

protected static InetAddress getInternetAddr(final String nic) {
    // Find the real network interface
    NetworkInterface iface = null;
    InetAddress ia = null;//from   w ww  .  ja  va2 s.  c o  m
    boolean foundNIC = false;
    try {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements() && foundNIC == false;) {
            iface = ifaces.nextElement();
            Util.logger.debug("Interface: " + iface.getDisplayName());
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements()
                    && foundNIC == false;) {
                ia = ips.nextElement();
                Util.logger.debug(ia.getCanonicalHostName() + " " + ia.getHostAddress());
                if (!ia.isLoopbackAddress()) {
                    Util.logger.debug("  Not a loopback address...");
                    if (!ia.getHostAddress().contains(":") && nic.equals(iface.getDisplayName())) {
                        Util.logger.debug("  Host address does not contain ':'");
                        Util.logger.debug("  Interface: " + iface.getName()
                                + " seems to be InternetInterface. I'll take it...");
                        foundNIC = true;
                    }
                }
            }
        }
    } catch (SocketException e) {
        Util.logger.error(e.getMessage());
    } finally {
        if (!foundNIC && nic != null) {
            Util.logger.error("Could not bind to network interface: " + nic);
            throw new RuntimeException("Could not bind to network interface: " + nic);
        } else if (!foundNIC) {
            Util.logger.error("Could not bind to any network interface");
            throw new RuntimeException("Could not bind to any network interface: ");
        }
    }
    return ia;
}

From source file:com.entertailion.java.fling.FlingFrame.java

private InterfaceAddress getPreferredInetAddress(String prefix) {
    InterfaceAddress selectedInterfaceAddress = null;
    try {/*from  w  w w . j  av a  2  s .com*/
        Enumeration<NetworkInterface> list = NetworkInterface.getNetworkInterfaces();

        while (list.hasMoreElements()) {
            NetworkInterface iface = list.nextElement();
            if (iface == null)
                continue;
            Log.d(LOG_TAG, "interface=" + iface.getName());
            Iterator<InterfaceAddress> it = iface.getInterfaceAddresses().iterator();
            while (it.hasNext()) {
                InterfaceAddress interfaceAddress = it.next();
                if (interfaceAddress == null)
                    continue;
                InetAddress address = interfaceAddress.getAddress();
                Log.d(LOG_TAG, "address=" + address);
                if (address instanceof Inet4Address) {
                    // Only pick an interface that is likely to be on the
                    // same subnet as the selected ChromeCast device
                    if (address.getHostAddress().toString().startsWith(prefix)) {
                        return interfaceAddress;
                    }
                }
            }
        }
    } catch (Exception ex) {
    }
    return selectedInterfaceAddress;
}

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

/**
 * Set the broadcast mask to use for NetBIOS name lookups
 * /*from w ww  .  ja v  a2 s .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.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;
    }/*from  w ww .j  av  a 2  s . c  o  m*/

    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:com.vuze.plugin.azVPN_PIA.Checker.java

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

    /**
    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, "pia.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("PIA 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, "pia.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);
        config.setUnsafeBooleanParameter("Enforce Bind IP", true);
        config.setUnsafeBooleanParameter("Check Bind IP On Start", true);

        config.setUnsafeBooleanParameter("upnp.enable", false);
        config.setUnsafeBooleanParameter("natpmp.enable", false);

        addReply(sReply, CHAR_GOOD, "pia.change.binding", new String[] { "" + newConfigBindIP,
                networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

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

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   ww w  .  jav a 2s.c om*/
    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;//from ww w.ja v  a2s  .  c om

    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;
}

From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java

/**
 * @return the host address to bind this service to
 *///  www  .jav a 2 s .com
protected InetAddress determineHostAddress() {
    NetworkInterface iface = determineNetworkInterface();
    InetAddress raw = null;
    for (Enumeration<InetAddress> interfaceAddresses = iface.getInetAddresses(); interfaceAddresses
            .hasMoreElements();) {
        if (!interfaceAddresses.hasMoreElements()) {
            String msg = String.format("Unable to find any network address for interface[%s] {%s}",
                    iface.getName(), iface.getDisplayName());
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
        raw = interfaceAddresses.nextElement();
        if (config.ipV6) {
            if (raw.getAddress().length == 6) {
                break;
            }
        } else if (raw.getAddress().length == 4) {
            break;
        }
    }
    if (raw == null) {
        String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(),
                iface.getDisplayName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    InetAddress address;
    try {
        address = InetAddress.getByName(raw.getCanonicalHostName());
    } catch (UnknownHostException e) {
        String msg = String.format("Unable to resolve network address [%s] for interface[%s] {%s}", raw,
                iface.getName(), iface.getDisplayName());
        logger.error(msg, e);
        throw new IllegalStateException(msg, e);
    }
    return address;
}

From source file:net.spfbl.core.Core.java

private static boolean hasInterface(String netInterface) {
    try {//from www. j ava  2 s .c  o  m
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            if (netInterface.equals(netint.getName())) {
                return true;
            }
        }
        return false;
    } catch (SocketException ex) {
        return false;
    }
}

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

/**
 * @return rebind sucessful, or rebinding to already bound address
 *///  www .ja  v  a  2 s  .co  m
private boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    /**
    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, "airvpn.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("AirVPN 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, "airvpn.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);
        config.setUnsafeBooleanParameter("Enforce Bind IP", true);
        config.setUnsafeBooleanParameter("Check Bind IP On Start", true);

        config.setUnsafeBooleanParameter("upnp.enable", false);
        config.setUnsafeBooleanParameter("natpmp.enable", false);

        addReply(sReply, CHAR_GOOD, "airvpn.change.binding", new String[] { "" + newConfigBindIP,
                networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

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