Example usage for java.net InetAddress equals

List of usage examples for java.net InetAddress equals

Introduction

In this page you can find the example usage for java.net InetAddress equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object against the specified object.

Usage

From source file:org.opennms.netmgt.model.OnmsNode.java

/**
 * <p>getIpInterfaceByIpAddress</p>
 *
 * @param ipAddress a {@link String} object.
 * @return a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
 */// w ww.j  ava  2s.  co  m
public OnmsIpInterface getIpInterfaceByIpAddress(InetAddress ipAddress) {
    for (OnmsIpInterface iface : getIpInterfaces()) {
        if (ipAddress.equals(iface.getIpAddress())) {
            return iface;
        }
    }
    return null;
}

From source file:at.alladin.rmbt.android.main.RMBTMainMenuFragment.java

/**
* 
*///from   w ww  .ja  v a  2 s .c o m
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    Log.i(DEBUG_TAG, "onCreate");
    pulseAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.pulse);
    interfaceTrafficGatherer = new InterfaceTrafficGatherer();
    informationCollector = new InformationCollector(getActivity(), false, false);
    speedFormat = new DecimalFormat(
            String.format("@@ %s", getActivity().getResources().getString(R.string.test_mbps)));

    ipv4CheckRunnable = new IpCheckRunnable(getActivity(), IpVersionType.V4, true);
    ipv4CheckRunnable.addListener(new OnIpCheckFinishedListener() {

        @Override
        public void onFinish(InetAddress privAddress, InetAddress pubAddress, InetAddress oldPrivAddress,
                InetAddress oldPubAddress) {
            if ((privAddress != null && !privAddress.equals(oldPrivAddress))
                    || (pubAddress != null && !pubAddress.equals(oldPubAddress))
                    || (privAddress == null && oldPrivAddress != null
                            || pubAddress == null && oldPubAddress != null)) {
                Log.d(DEBUG_TAG, "new ipv4, run captive portal check...");
                ((RMBTMainActivity) getActivity()).getNetworkInfoCollector().checkForCaptivePortal();
            }
        }
    });

    ipv6CheckRunnable = new IpCheckRunnable(getActivity(), IpVersionType.V6, true);
    ipv6CheckRunnable.addListener(new OnIpCheckFinishedListener() {

        @Override
        public void onFinish(InetAddress privAddress, InetAddress pubAddress, InetAddress oldPrivAddress,
                InetAddress oldPubAddress) {
            if ((privAddress != null && !privAddress.equals(oldPrivAddress))
                    || (pubAddress != null && !pubAddress.equals(oldPubAddress))
                    || (privAddress == null && oldPrivAddress != null
                            || pubAddress == null && oldPubAddress != null)) {
                Log.d(DEBUG_TAG, "new ipv6, run captive portal check...");
                ((RMBTMainActivity) getActivity()).getNetworkInfoCollector().checkForCaptivePortal();
            }
        }
    });

    networkWatcherRunnable = new NetworkWatcherRunnable(getActivity());
    networkWatcherRunnable.addListener(new OnActiveNetworkChangeListener() {

        @Override
        public void onChange(Set<InetAddress> oldInterfaceSet, Set<InetAddress> newInterfaceSet, String oldSsid,
                String newSsid) {
            ipv4CheckRunnable.clearIps();
            ipv6CheckRunnable.clearIps();
            ((RMBTMainActivity) getActivity()).getNetworkInfoCollector().checkForCaptivePortal();
        }
    });
}

From source file:net.sbbi.upnp.DiscoveryListener.java

private void listenBroadCast() throws IOException {

    skt.receive(input);//ww  w.  j av a  2 s  . c o  m
    InetAddress from = input.getAddress();
    String received = new String(input.getData(), input.getOffset(), input.getLength());
    HttpResponse msg = null;
    try {
        msg = new HttpResponse(received);
    } catch (IllegalArgumentException ex) {
        // crappy http sent
        if (log.isDebugEnabled())
            log.debug("Skipping uncompliant HTTP message " + received);
        return;
    }
    String header = msg.getHeader();
    if (header != null && header.startsWith("HTTP/1.1 200 OK") && msg.getHTTPHeaderField("st") != null) {
        // probably a search repsonse !
        String deviceDescrLoc = msg.getHTTPHeaderField("location");
        if (deviceDescrLoc == null || deviceDescrLoc.trim().length() == 0) {
            if (log.isDebugEnabled())
                log.debug("Skipping SSDP message, missing HTTP header 'location' field");
            return;
        }
        URL loc = new URL(deviceDescrLoc);
        if (MATCH_IP) {
            InetAddress locHost = InetAddress.getByName(loc.getHost());
            if (!from.equals(locHost)) {
                log.warn("Discovery message sender IP " + from + " does not match device description IP "
                        + locHost + " skipping device, set the net.sbbi.upnp.ddos.matchip system property"
                        + " to false to avoid this check");
                return;
            }
        }
        if (log.isDebugEnabled())
            log.debug("Processing " + deviceDescrLoc + " device description location");
        String st = msg.getHTTPHeaderField("st");
        if (st == null || st.trim().length() == 0) {
            if (log.isDebugEnabled())
                log.debug("Skipping SSDP message, missing HTTP header 'st' field");
            return;
        }
        String usn = msg.getHTTPHeaderField("usn");
        if (usn == null || usn.trim().length() == 0) {
            if (log.isDebugEnabled())
                log.debug("Skipping SSDP message, missing HTTP header 'usn' field");
            return;
        }
        String maxAge = msg.getHTTPFieldElement("Cache-Control", "max-age");
        if (maxAge == null || maxAge.trim().length() == 0) {
            if (log.isDebugEnabled())
                log.debug("Skipping SSDP message, missing HTTP header 'max-age' field");
            return;
        }
        String server = msg.getHTTPHeaderField("server");
        if (server == null || server.trim().length() == 0) {
            if (log.isDebugEnabled())
                log.debug("Skipping SSDP message, missing HTTP header 'server' field");
            return;
        }

        String udn = usn;
        int index = udn.indexOf("::");
        if (index != -1)
            udn = udn.substring(0, index);
        synchronized (REGISTRATION_PROCESS) {
            Set handlers = (Set) registeredHandlers.get(st);
            if (handlers != null) {
                for (Iterator i = handlers.iterator(); i.hasNext();) {
                    DiscoveryResultsHandler handler = (DiscoveryResultsHandler) i.next();
                    handler.discoveredDevice(usn, udn, st, maxAge, loc, server);
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Skipping uncompliant HTTP message " + received);
    }
}

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  a v  a2 s.  c  o  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.eclipse.jubula.client.ui.rcp.widgets.autconfig.AutConfigComponent.java

/**
 * @return true if the aut config is for the currently connected AUT starter
 *//*from  w  ww  .ja  v a2  s.c o  m*/
protected boolean isRemoteRequest() {
    boolean enable;
    try {
        final AutAgent currentServer = ConnectAutAgentBP.getInstance().getCurrentAutAgent();
        if (currentServer == null) {
            return false;
        }
        if (isLocalhost()) {
            return false;
        }

        final String serverName = getServerCombo().getText().toLowerCase();
        final InetAddress serverAddress = InetAddress.getByName(serverName);
        final String canonicalServerName = serverAddress.getCanonicalHostName().toLowerCase();

        final String currentServerName = currentServer.getName().toLowerCase();
        final InetAddress currentServerAddress = InetAddress.getByName(currentServerName);
        final String canonicalCurrentServerName = currentServerAddress.getCanonicalHostName().toLowerCase();

        enable = currentServerName.equals(serverName) || currentServerAddress.equals(serverAddress)
                || canonicalCurrentServerName.equals(canonicalServerName);
    } catch (UnknownHostException e) {
        enable = false;
    }

    return enable;
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * This method is responsible for processing 'interfacReparented' events.
 * An 'interfaceReparented' event will have old and new nodeId parms
 * associated with it. All CollectableService objects in the service
 * updates map which match the event's interface address and the SNMP
 * service have a reparenting update associated with them. When the
 * scheduler next pops one of these services from an interval queue for
 * collection all of the RRDs associated with the old nodeId are moved
 * under the new nodeId and the nodeId of the collectable service is
 * updated to reflect the interface's new parent nodeId.
 *
 * @param event The event to process./*from  ww  w .j a  v a  2  s. c  om*/
 * @throws InsufficientInformationException
 */
private void handleInterfaceReparented(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);
    EventUtils.checkInterface(event);

    LOG.debug("interfaceReparentedHandler:  processing interfaceReparented event for {}", event.getInterface());

    // Verify that the event has an interface associated with it
    if (event.getInterface() == null) {
        return;
    }

    // Extract the old and new nodeId's from the event parms
    String oldNodeIdStr = null;
    String newNodeIdStr = null;
    String parmName = null;
    Value parmValue = null;
    String parmContent = null;

    for (Parm parm : event.getParmCollection()) {
        parmName = parm.getParmName();
        parmValue = parm.getValue();
        if (parmValue == null) {
            continue;
        } else {
            parmContent = parmValue.getContent();
        }

        // old nodeid
        if (parmName.equals(EventConstants.PARM_OLD_NODEID)) {
            oldNodeIdStr = parmContent;
        }

        // new nodeid
        else {
            if (parmName.equals(EventConstants.PARM_NEW_NODEID)) {
                newNodeIdStr = parmContent;
            }
        }
    }

    // Only proceed provided we have both an old and a new nodeId
    //
    if (oldNodeIdStr == null || newNodeIdStr == null) {
        LOG.warn("interfaceReparentedHandler: old and new nodeId parms are required, unable to process.");
        return;
    }

    // Iterate over the CollectableService objects in the services
    // list looking for entries which share the same interface
    // address as the reparented interface. Mark any matching objects
    // for reparenting.
    //
    // The next time the service is scheduled for execution it
    // will move all of the RRDs associated
    // with the old nodeId under the new nodeId and update the service's
    // SnmpMonitor.NodeInfo attribute to reflect the new nodeId. All
    // subsequent collections will then be updating the appropriate RRDs.
    //
    OnmsIpInterface iface = null;
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        Iterator<CollectableService> iter = getCollectableServices().iterator();
        while (iter.hasNext()) {
            cSvc = iter.next();

            InetAddress addr = (InetAddress) cSvc.getAddress();
            if (addr.equals(event.getInterfaceAddress())) {
                synchronized (cSvc) {
                    // Got a match!
                    LOG.debug("interfaceReparentedHandler: got a CollectableService match for {}",
                            event.getInterface());

                    // Retrieve the CollectorUpdates object associated
                    // with
                    // this CollectableService.
                    CollectorUpdates updates = cSvc.getCollectorUpdates();
                    if (iface == null) {
                        iface = getIpInterface(event.getNodeid().intValue(), event.getInterface());
                    }

                    // Now set the reparenting flag
                    updates.markForReparenting(oldNodeIdStr, newNodeIdStr, iface);
                    LOG.debug("interfaceReparentedHandler: marking {} for reparenting for service SNMP.",
                            event.getInterface());
                }
            }
        }
    }

    LOG.debug("interfaceReparentedHandler: processing of interfaceReparented event for interface {} completed.",
            event.getInterface());
}

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 w  w .j a va2 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:org.lealone.cluster.locator.TokenMetaData.java

/**
 * Update token map with a set of token/endpoint pairs in normal state.
 *
 * Prefer this whenever there are multiple pairs to update, as each update (whether a single or multiple)
 * is expensive (lealone-3831)./*from  w  w w  . j  a va2 s . c o m*/
 *
 * @param endpointTokens
 */
public void updateNormalTokens(Multimap<InetAddress, Token> endpointTokens) {
    if (endpointTokens.isEmpty())
        return;

    lock.writeLock().lock();
    try {
        boolean shouldSortTokens = false;
        for (InetAddress endpoint : endpointTokens.keySet()) {
            Collection<Token> tokens = endpointTokens.get(endpoint);

            assert tokens != null && !tokens.isEmpty();

            bootstrapTokens.removeValue(endpoint);
            tokenToEndpointMap.removeValue(endpoint);
            topology.addEndpoint(endpoint);
            leavingEndpoints.remove(endpoint);
            removeFromMoving(endpoint); // also removing this endpoint from moving

            for (Token token : tokens) {
                InetAddress prev = tokenToEndpointMap.put(token, endpoint);
                if (!endpoint.equals(prev)) {
                    if (prev != null)
                        logger.warn("Token {} changing ownership from {} to {}", token, prev, endpoint);
                    shouldSortTokens = true;
                }
            }
        }

        if (shouldSortTokens)
            sortedTokens = sortTokens();
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:uk.ac.horizon.ubihelper.service.PeerManager.java

private DnsClient getDnsClient(String name, int type, InetAddress dest) {
    ArrayList<DnsClient> dcs = dnsClients.get(name);
    for (int i = 0; dcs != null && i < dcs.size(); i++) {
        DnsClient dc = dcs.get(i);//from  w ww . j  av a2  s  . co m
        if (dc.getAge() > MAX_QUERY_AGE) {
            dcs.remove(i);
            i--;
            continue;
        }
        if (type == dc.getQuery().type && (dest == null || dest.equals(dc.getDestination())))
            return dc;
    }
    return null;
}

From source file:org.opennms.netmgt.collectd.Collectd.java

/**
 * This method is responsible for processing 'interfacReparented' events.
 * An 'interfaceReparented' event will have old and new nodeId parms
 * associated with it. All CollectableService objects in the service
 * updates map which match the event's interface address and the SNMP
 * service have a reparenting update associated with them. When the
 * scheduler next pops one of these services from an interval queue for
 * collection all of the RRDs associated with the old nodeId are moved
 * under the new nodeId and the nodeId of the collectable service is
 * updated to reflect the interface's new parent nodeId.
 * /*from  ww  w.  j  a v a2s  .co  m*/
 * @param event
 *            The event to process.
 * @throws InsufficientInformationException
 */
private void handleInterfaceReparented(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);
    EventUtils.checkInterface(event);

    LOG.debug("interfaceReparentedHandler:  processing interfaceReparented event for {}", event.getInterface());

    // Verify that the event has an interface associated with it
    if (event.getInterface() == null)
        return;

    // Extract the old and new nodeId's from the event parms
    String oldNodeIdStr = null;
    String newNodeIdStr = null;
    String parmName = null;
    Value parmValue = null;
    String parmContent = null;

    for (Parm parm : event.getParmCollection()) {
        parmName = parm.getParmName();
        parmValue = parm.getValue();
        if (parmValue == null)
            continue;
        else
            parmContent = parmValue.getContent();

        // old nodeid
        if (parmName.equals(EventConstants.PARM_OLD_NODEID)) {
            oldNodeIdStr = parmContent;
        }

        // new nodeid
        else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) {
            newNodeIdStr = parmContent;
        }
    }

    // Only proceed provided we have both an old and a new nodeId
    //
    if (oldNodeIdStr == null || newNodeIdStr == null) {
        LOG.warn("interfaceReparentedHandler: old and new nodeId parms are required, unable to process.");
        return;
    }

    // Iterate over the CollectableService objects in the services
    // list looking for entries which share the same interface
    // address as the reparented interface. Mark any matching objects
    // for reparenting.
    //
    // The next time the service is scheduled for execution it
    // will move all of the RRDs associated
    // with the old nodeId under the new nodeId and update the service's
    // SnmpMonitor.NodeInfo attribute to reflect the new nodeId. All
    // subsequent collections will then be updating the appropriate RRDs.
    //
    OnmsIpInterface iface = null;
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        Iterator<CollectableService> iter = getCollectableServices().iterator();
        while (iter.hasNext()) {
            cSvc = iter.next();

            InetAddress addr = (InetAddress) cSvc.getAddress();
            if (addr.equals(event.getInterfaceAddress())) {
                synchronized (cSvc) {
                    // Got a match!
                    LOG.debug("interfaceReparentedHandler: got a CollectableService match for {}",
                            event.getInterface());

                    // Retrieve the CollectorUpdates object associated
                    // with
                    // this CollectableService.
                    CollectorUpdates updates = cSvc.getCollectorUpdates();
                    if (iface == null) {
                        iface = getIpInterface(event.getNodeid().intValue(), event.getInterface());
                    }

                    // Now set the reparenting flag
                    updates.markForReparenting(oldNodeIdStr, newNodeIdStr, iface);
                    LOG.debug("interfaceReparentedHandler: marking {} for reparenting for service SNMP.",
                            event.getInterface());
                }
            }
        }
    }

    LOG.debug("interfaceReparentedHandler: processing of interfaceReparented event for interface {} completed.",
            event.getInterface());
}