Example usage for java.net InetAddress isLoopbackAddress

List of usage examples for java.net InetAddress isLoopbackAddress

Introduction

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

Prototype

public boolean isLoopbackAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a loopback address.

Usage

From source file:eu.faircode.netguard.ServiceSinkhole.java

public static List<InetAddress> getDns(Context context) {
    List<InetAddress> listDns = new ArrayList<>();
    List<String> sysDns = Util.getDefaultDNS(context);

    // Get custom DNS servers
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean ip6 = prefs.getBoolean("ip6", true);
    String vpnDns1 = prefs.getString("dns", null);
    String vpnDns2 = prefs.getString("dns2", null);
    Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2);

    if (vpnDns1 != null)
        try {//from   w  w w . ja  v  a2  s. co  m
            InetAddress dns = InetAddress.getByName(vpnDns1);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ignored) {
        }

    if (vpnDns2 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns2);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

    // Use system DNS servers only when no two custom DNS servers specified
    if (listDns.size() <= 1)
        for (String def_dns : sysDns)
            try {
                InetAddress ddns = InetAddress.getByName(def_dns);
                if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress())
                        && (ip6 || ddns instanceof Inet4Address))
                    listDns.add(ddns);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

    // Remove local DNS servers when not routing LAN
    boolean lan = prefs.getBoolean("lan", false);
    boolean use_hosts = prefs.getBoolean("filter", false) && prefs.getBoolean("use_hosts", false);
    if (lan && use_hosts) {
        List<InetAddress> listLocal = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            if (nis != null)
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback()) {
                        List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                        if (ias != null)
                            for (InterfaceAddress ia : ias) {
                                InetAddress hostAddress = ia.getAddress();
                                BigInteger host = new BigInteger(1, hostAddress.getAddress());

                                int prefix = ia.getNetworkPrefixLength();
                                BigInteger mask = BigInteger.valueOf(-1)
                                        .shiftLeft(hostAddress.getAddress().length * 8 - prefix);

                                for (InetAddress dns : listDns)
                                    if (hostAddress.getAddress().length == dns.getAddress().length) {
                                        BigInteger ip = new BigInteger(1, dns.getAddress());

                                        if (host.and(mask).equals(ip.and(mask))) {
                                            Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix
                                                    + " dns=" + dns);
                                            listLocal.add(dns);
                                        }
                                    }
                            }
                    }
                }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        List<InetAddress> listDns4 = new ArrayList<>();
        List<InetAddress> listDns6 = new ArrayList<>();
        try {
            listDns4.add(InetAddress.getByName("8.8.8.8"));
            listDns4.add(InetAddress.getByName("8.8.4.4"));
            if (ip6) {
                listDns6.add(InetAddress.getByName("2001:4860:4860::8888"));
                listDns6.add(InetAddress.getByName("2001:4860:4860::8844"));
            }

        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        for (InetAddress dns : listLocal) {
            listDns.remove(dns);
            if (dns instanceof Inet4Address) {
                if (listDns4.size() > 0) {
                    listDns.add(listDns4.get(0));
                    listDns4.remove(0);
                }
            } else {
                if (listDns6.size() > 0) {
                    listDns.add(listDns6.get(0));
                    listDns6.remove(0);
                }
            }
        }
    }

    return listDns;
}

From source file:kx.c.java

/**
 * Prepare socket for kdb+ ipc comms//from w ww  . j a v  a 2s  .  co m
 * @param x socket to setup
 * @throws IOException an I/O error occurs.
 */
void io(Socket x) throws IOException {
    s = x;
    s.setTcpNoDelay(true);
    InetAddress addr = s.getInetAddress();
    l = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
    i = new DataInputStream(s.getInputStream());
    o = s.getOutputStream();
    s.setKeepAlive(true);
}

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  . ja  v  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.alliander.osgp.adapter.protocol.oslp.elster.infra.networking.OslpDeviceService.java

/**
 * Return the correct port, depending on loopback or external.
 *///from w  w w  .j a  va 2  s .  co m
private InetSocketAddress createAddress(final InetAddress address) {
    if (address.isLoopbackAddress()) {
        return new InetSocketAddress(address, this.oslpPortClientLocal);
    }

    return new InetSocketAddress(address, this.oslpPortClient);
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

static String getNetAddressInfo() {
    try {/*ww w .  j a va 2 s.c o m*/
        StringBuffer sb = new StringBuffer();

        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String addr = inetAddress.getHostAddress();

                    if (!TextUtils.isEmpty(addr)) {
                        if (sb.length() == 0) {
                            sb.append(addr);
                        } else {
                            sb.append(", ").append(addr); //$NON-NLS-1$
                        }
                    }
                }
            }
        }

        String netAddress = sb.toString();

        if (!TextUtils.isEmpty(netAddress)) {
            return netAddress;
        }
    } catch (SocketException e) {
        Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
    }

    return null;
}

From source file:org.pentaho.di.core.Const.java

/**
 * Determins the IP address of the machine Kettle is running on.
 *
 * @return The IP address//  w w  w .j  a v a 2  s. c o m
 */
public static final String getIPAddress() throws Exception {
    Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
    while (enumInterfaces.hasMoreElements()) {
        NetworkInterface nwi = enumInterfaces.nextElement();
        Enumeration<InetAddress> ip = nwi.getInetAddresses();
        while (ip.hasMoreElements()) {
            InetAddress in = ip.nextElement();
            if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) {
                return in.getHostAddress();
            }
        }
    }
    return "127.0.0.1";
}

From source file:org.pentaho.di.core.Const.java

/**
 * Get the primary IP address tied to a network interface (excluding loop-back etc)
 *
 * @param networkInterfaceName/*from w w w .  j av a2s .co m*/
 *          the name of the network interface to interrogate
 * @return null if the network interface or address wasn't found.
 *
 * @throws SocketException
 *           in case of a security or network error
 */
public static final String getIPAddress(String networkInterfaceName) throws SocketException {
    NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName);
    Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses();
    while (ipAddresses.hasMoreElements()) {
        InetAddress inetAddress = ipAddresses.nextElement();
        if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) {
            String hostname = inetAddress.getHostAddress();
            return hostname;
        }
    }
    return null;
}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

/**
 * This method is responsible for determining if a node already exists in
 * the database for the current interface. If the IfCollector object
 * contains a valid SNMP collection, an attempt will be made to look up in
 * the database each interface contained in the SNMP collection's ifTable.
 * If an interface is found to already exist in the database a DbNodeEntry
 * object will be created from it and returned. If the IfCollector object
 * does not contain a valid SNMP collection or if none of the interfaces
 * exist in the database null is returned.
 *
 * @param dbc       Connection to the database.
 * @param collector Interface collector object
 * @return dbNodeEntry Returns null if a node does not already exist in
 * the database, otherwise returns the DbNodeEntry object for the
 * node under which the current interface/IP address should be
 * added.//from  ww w  .j  av  a2  s .  c  om
 * @throws java.sql.SQLException Thrown if an error occurs retrieving the parent nodeid from
 *                               the database.
 */
private DbNodeEntry getExistingNodeEntry(Connection dbc, IfCollector collector) throws SQLException {
    LOG.debug("getExistingNodeEntry: checking for current target: {}", collector.getTarget());

    // Do we have any additional interface information collected via SNMP?
    // If not simply return, there is nothing to check
    if (!collector.hasSnmpCollection() || collector.getSnmpCollector().failed()) {
        return null;
    }

    // Next verify that ifTable and ipAddrTable entries were collected
    IfSnmpCollector snmpc = collector.getSnmpCollector();
    IfTable ifTable = null;
    IpAddrTable ipAddrTable = null;

    if (snmpc.hasIfTable()) {
        ifTable = snmpc.getIfTable();
    }

    if (snmpc.hasIpAddrTable()) {
        ipAddrTable = snmpc.getIpAddrTable();
    }

    if (ifTable == null || ipAddrTable == null) {
        return null;
    }

    // SQL statement prefix
    StringBuffer sqlBuffer = new StringBuffer(SQL_RETRIEVE_INTERFACE_NODEID_PREFIX);
    boolean firstAddress = true;

    // Loop through the interface table entries and see if any already
    // exist in the database.
    List<String> ipaddrsOfNewNode = new ArrayList<String>();
    List<String> ipaddrsOfOldNode = new ArrayList<String>();

    for (IfTableEntry ifEntry : ifTable) {

        if (ifEntry.getIfIndex() == null) {
            LOG.debug("getExistingNodeEntry:  Breaking from loop");
            break;
        }

        //
        // Get ifIndex
        //
        int ifIndex = ifEntry.getIfIndex().intValue();

        //
        // Get ALL IP Addresses for this ifIndex
        //
        List<InetAddress> ipAddrs = ipAddrTable.getIpAddresses(ifIndex);
        LOG.debug("getExistingNodeEntry: number of interfaces retrieved for ifIndex {} is: {}", ifIndex,
                ipAddrs.size());

        // Iterate over IP address list and add each to the sql buffer
        //
        for (InetAddress ipAddress : ipAddrs) {

            //
            // Skip interface if no IP address or if IP address is
            // "0.0.0.0"
            // or if this interface is of type loopback
            if (ipAddress == null || str(ipAddress).equals("0.0.0.0") || ipAddress.isLoopbackAddress()) {
                continue;
            }

            if (firstAddress) {
                sqlBuffer.append("ipaddr='").append(str(ipAddress)).append("'");
                firstAddress = false;
            } else {
                sqlBuffer.append(" OR ipaddr='").append(str(ipAddress)).append("'");
            }

            ipaddrsOfNewNode.add(str(ipAddress));
        }
    } // end while

    // Make sure we added at least one address to the SQL query
    //
    if (firstAddress) {
        return null;
    }

    // Prepare the db statement in advance
    //
    LOG.debug("getExistingNodeEntry: issuing SQL command: {}", sqlBuffer.toString());

    int nodeID = -1;
    PreparedStatement stmt;
    final DBUtils d = new DBUtils(getClass());

    try {
        stmt = dbc.prepareStatement(sqlBuffer.toString());
        d.watch(stmt);

        // Do any of the IP addrs already exist in the database under another node?
        ResultSet rs = stmt.executeQuery();
        d.watch(rs);
        if (rs.next()) {
            nodeID = rs.getInt(1);
            LOG.debug("getExistingNodeEntry: target {}/{}", str(collector.getTarget()), nodeID);
            rs = null;
        }
    } finally {
        d.cleanUp();
    }

    if (nodeID == -1) {
        return null;
    }

    try {
        stmt = dbc.prepareStatement(SQL_RETRIEVE_IPINTERFACES_ON_NODEID);
        d.watch(stmt);
        stmt.setInt(1, nodeID);

        ResultSet rs = stmt.executeQuery();
        d.watch(rs);
        while (rs.next()) {
            String ipaddr = rs.getString(1);
            if (!ipaddr.equals("0.0.0.0")) {
                ipaddrsOfOldNode.add(ipaddr);
            }
        }
    } finally {
        d.cleanUp();
    }

    if (ipaddrsOfNewNode.containsAll(ipaddrsOfOldNode)) {
        LOG.debug("getExistingNodeEntry: found one of the addrs under existing node: {}", nodeID);
        return DbNodeEntry.get(nodeID);
    } else {
        String dupIpaddr = getDuplicateIpaddress(ipaddrsOfOldNode, ipaddrsOfNewNode);
        createAndSendDuplicateIpaddressEvent(nodeID, dupIpaddr);
        return null;
    }
}

From source file:org.mobicents.servlet.restcomm.telephony.CallManager.java

public void bye(final Object message) throws IOException {
    final ActorRef self = self();
    final SipServletRequest request = (SipServletRequest) message;
    final SipApplicationSession application = request.getApplicationSession();

    // if this response is coming from a client that is in a p2p session with another registered client
    // we will just proxy the response
    SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
    if (linkedB2BUASession != null) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Got BYE request: \n %s", request));
        }//from w ww . ja v a2  s .  co m

        //Prepare the BYE request to the linked session
        request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
        SipServletRequest clonedBye = linkedB2BUASession.createRequest("BYE");
        linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedBye);

        if (patchForNatB2BUASessions) {
            // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
            SipURI toInetUri = (SipURI) request.getSession().getAttribute("toInetUri");
            SipURI fromInetUri = (SipURI) request.getSession().getAttribute("fromInetUri");
            InetAddress byeRURI = null;
            try {
                byeRURI = InetAddress.getByName(((SipURI) clonedBye.getRequestURI()).getHost());
            } catch (UnknownHostException e) {
            }
            if (toInetUri != null && byeRURI == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (toInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (fromInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + fromInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(fromInetUri);
            } else if (toInetUri == null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "Public IP toInetUri from SipSession is null, will check LB headers from last Response");
                }
                final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
                String initialPortBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemotePort");
                if (initialIpBeforeLB != null) {
                    if (initialPortBeforeLB == null)
                        initialPortBeforeLB = "5060";
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use Initial Remote Address "
                                + initialIpBeforeLB + ":" + initialPortBeforeLB
                                + " for the cloned BYE request");
                    }
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = sipFactory.createSipURI(null, realIP);
                    clonedBye.setRequestURI(uri);
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("LB Headers are also null");
                    }
                }
            }
        }
        B2BUAHelper.updateCDR(request, CallStateChanged.State.COMPLETED);
        //Prepare 200 OK for received BYE
        SipServletResponse okay = request.createResponse(Response.OK);
        okay.send();
        //Send the Cloned BYE
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Will send out Cloned BYE request: \n %s", clonedBye));
        }
        clonedBye.send();
    } else {
        final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
        if (call != null)
            call.tell(request, self);
    }
}