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:com.netxforge.oss2.config.AmiPeerFactory.java

/**
 * <p>getAgentConfig</p>//from ww w.  ja  va 2s. co  m
 *
 * @param agentInetAddress a {@link java.net.InetAddress} object.
 * @return a {@link org.opennms.protocols.ami.AmiAgentConfig} object.
 */
public AmiAgentConfig getAgentConfig(final InetAddress agentInetAddress) {
    getReadLock().lock();

    try {
        if (m_config == null)
            return new AmiAgentConfig(agentInetAddress);

        final AmiAgentConfig agentConfig = new AmiAgentConfig(agentInetAddress);

        //Now set the defaults from the m_config
        setAmiAgentConfig(agentConfig, new Definition());

        // Attempt to locate the node
        DEFLOOP: for (final Definition def : m_config.getDefinitionCollection()) {
            // check the specifics first
            for (String saddr : def.getSpecificCollection()) {
                saddr = saddr.trim();
                final InetAddress addr = InetAddressUtils.addr(saddr);
                if (addr.equals(agentConfig.getAddress())) {
                    setAmiAgentConfig(agentConfig, def);
                    break DEFLOOP;
                }
            }

            // check the ranges
            for (final Range rng : def.getRangeCollection()) {
                if (InetAddressUtils.isInetAddressInRange(InetAddressUtils.str(agentConfig.getAddress()),
                        rng.getBegin(), rng.getEnd())) {
                    setAmiAgentConfig(agentConfig, def);
                    break DEFLOOP;
                }
            }

            // check the matching IP expressions
            for (final String ipMatch : def.getIpMatchCollection()) {
                if (IPLike.matches(InetAddressUtils.str(agentInetAddress), ipMatch)) {
                    setAmiAgentConfig(agentConfig, def);
                    break DEFLOOP;
                }
            }

        } // end DEFLOOP

        if (agentConfig == null)
            setAmiAgentConfig(agentConfig, new Definition());

        return agentConfig;
    } finally {
        getReadLock().unlock();
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static boolean isLocalAddress(final InetAddress addr) {
    final InetAddress[] addrs = getAllLocalInetAddresses();

    if (addrs != null) {
        for (final InetAddress self : addrs) {
            if (self.equals(addr)) {
                return true;
            }//  ww  w .j  a  v a  2  s.co  m
        }
    }
    return false;
}

From source file:org.opennms.netmgt.config.WmiPeerFactory.java

/**
 * <p>getAgentConfig</p>/*w  w  w. ja  v a 2s . c  o  m*/
 *
 * @param agentInetAddress a {@link java.net.InetAddress} object.
 * @return a {@link org.opennms.protocols.wmi.WmiAgentConfig} object.
 */
public synchronized WmiAgentConfig getAgentConfig(InetAddress agentInetAddress) {

    if (m_config == null) {
        return new WmiAgentConfig(agentInetAddress);
    }

    WmiAgentConfig agentConfig = new WmiAgentConfig(agentInetAddress);

    //Now set the defaults from the m_config
    setWmiAgentConfig(agentConfig, new Definition());

    // Attempt to locate the node
    //
    Enumeration<Definition> edef = m_config.enumerateDefinition();
    DEFLOOP: while (edef.hasMoreElements()) {
        Definition def = edef.nextElement();

        // check the specifics first
        for (String saddr : def.getSpecificCollection()) {
            InetAddress addr = InetAddressUtils.addr(saddr);
            if (addr.equals(agentConfig.getAddress())) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }

        // check the ranges
        for (Range rng : def.getRangeCollection()) {
            if (InetAddressUtils.isInetAddressInRange(InetAddressUtils.str(agentConfig.getAddress()),
                    rng.getBegin(), rng.getEnd())) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }

        // check the matching IP expressions
        //
        for (String ipMatch : def.getIpMatchCollection()) {
            if (IPLike.matches(InetAddressUtils.str(agentInetAddress), ipMatch)) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }

    } // end DEFLOOP

    if (agentConfig == null) {

        Definition def = new Definition();
        setWmiAgentConfig(agentConfig, def);
    }

    return agentConfig;

}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

private List<InetAddress> getControllerIPAddresses(Connection connection) {
    List<InetAddress> controllers = null;
    InetAddress controllerIP = null;

    controllers = new ArrayList<InetAddress>();
    String addressString = System.getProperty("ovsdb.controller.address");

    if (addressString != null) {
        try {// w w w  .  ja va2  s . c o m
            controllerIP = InetAddress.getByName(addressString);
            if (controllerIP != null) {
                controllers.add(controllerIP);
                return controllers;
            }
        } catch (UnknownHostException e) {
            logger.error("Host {} is invalid", addressString);
        }
    }

    if (clusterServices != null) {
        controllers = clusterServices.getClusteredControllers();
        if (controllers != null && controllers.size() > 0) {
            if (controllers.size() == 1) {
                InetAddress controller = controllers.get(0);
                if (!controller.equals(InetAddress.getLoopbackAddress())) {
                    return controllers;
                }
            } else {
                return controllers;
            }
        }
    }

    addressString = System.getProperty("of.address");

    if (addressString != null) {
        try {
            controllerIP = InetAddress.getByName(addressString);
            if (controllerIP != null) {
                controllers.add(controllerIP);
                return controllers;
            }
        } catch (UnknownHostException e) {
            logger.error("Host {} is invalid", addressString);
        }
    }

    try {
        controllerIP = ((InetSocketAddress) connection.getChannel().localAddress()).getAddress();
        controllers.add(controllerIP);
        return controllers;
    } catch (Exception e) {
        logger.debug("Invalid connection provided to getControllerIPAddresses", e);
    }
    return controllers;
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Tests whether or not there is a match between the given IP address and the candidates.
 * //  w  ww.j  av a  2 s  . c  om
 * @param ip
 * @param candidateIps
 * @return <code>true</code> if there is a match
 * @should return true if list is empty
 * @should return false if there is no match
 * @should return true for exact match
 * @should return true for match with submask
 * @should return false if there is no match with submask
 * @should return true for exact ipv6 match
 * @should throw IllegalArgumentException for invalid mask
 */
public static boolean ipMatches(String ip, List<String> candidateIps) {
    if (candidateIps.isEmpty()) {
        return true;
    }

    InetAddress address;
    try {
        address = InetAddress.getByName(ip);
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Invalid IP in the ip parameter" + ip, e);
    }

    for (String candidateIp : candidateIps) {
        // split IP and mask
        String[] candidateIpPattern = candidateIp.split("/");

        InetAddress candidateAddress;
        try {
            candidateAddress = InetAddress.getByName(candidateIpPattern[0]);
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("Invalid IP in the candidateIps parameter", e);
        }

        if (candidateIpPattern.length == 1) { // there's no mask
            if (address.equals(candidateAddress)) {
                return true;
            }
        } else {
            if (address.getAddress().length != candidateAddress.getAddress().length) {
                continue;
            }

            int bits = Integer.parseInt(candidateIpPattern[1]);
            if (candidateAddress.getAddress().length < Math.ceil((double) bits / 8)) {
                throw new IllegalArgumentException(
                        "Invalid mask " + bits + " for IP " + candidateIp + " in the candidateIps parameter");
            }

            // compare bytes based on the given mask
            boolean matched = true;
            for (int bytes = 0; bits > 0; bytes++, bits -= 8) {
                int mask = 0x000000FF; // mask the entire byte
                if (bits < 8) {
                    // mask only some first bits of a byte
                    mask = (mask << (8 - bits));
                }
                if ((address.getAddress()[bytes] & mask) != (candidateAddress.getAddress()[bytes] & mask)) {
                    matched = false;
                    break;
                }
            }
            if (matched) {
                return true;
            }
        }

    }
    return false;
}

From source file:com.bigdata.dastor.locator.TokenMetadata.java

public void updateNormalToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();/*from   ww  w . j  a v a  2  s  .  c o m*/
    try {
        bootstrapTokens.inverse().remove(endpoint);
        tokenToEndPointMap.inverse().remove(endpoint);
        if (!endpoint.equals(tokenToEndPointMap.put(token, endpoint))) {
            sortedTokens = sortTokens();
        }
        leavingEndPoints.remove(endpoint);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.apache.cassandra.locator.TokenMetadata.java

public void addBootstrapToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();//w  ww.j  ava 2  s.c o  m
    try {
        InetAddress oldEndpoint;

        oldEndpoint = bootstrapTokens.get(token);
        if (oldEndpoint != null && !oldEndpoint.equals(endpoint))
            throw new RuntimeException("Bootstrap Token collision between " + oldEndpoint + " and " + endpoint
                    + " (token " + token);

        oldEndpoint = tokenToEndpointMap.get(token);
        if (oldEndpoint != null && !oldEndpoint.equals(endpoint))
            throw new RuntimeException("Bootstrap Token collision between " + oldEndpoint + " and " + endpoint
                    + " (token " + token);

        bootstrapTokens.inverse().remove(endpoint);
        bootstrapTokens.put(token, endpoint);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageReceiver.java

protected ServerSocket createServerSocket(URI uri) throws IOException {
    String host = uri.getHost();/*  w w w .  j av  a2 s  .c  om*/
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}

From source file:org.openhab.io.neeo.internal.discovery.MdnsBrainDiscovery.java

/**
 * Consider whether the {@link ServiceInfo} is for a NEEO brain. We first get the info via
 * {@link #getNeeoBrainInfo(ServiceInfo)} and then attempt to connect to it to retrieve the {@link NeeoSystemInfo}.
 * If successful and the brain has not been already discovered, a
 * {@link #fireDiscovered(NeeoSystemInfo, InetAddress)} is issued.
 *
 * @param info the non-null {@link ServiceInfo}
 * @param attempts the number of attempts that have been made
 *///from w  ww  .  ja  v  a 2  s.  c o  m
private void considerService(ServiceInfo info, int attempts) {
    Objects.requireNonNull(info, "info cannot be null");
    if (attempts < 1) {
        throw new IllegalArgumentException("attempts cannot be below 1: " + attempts);
    }

    final Entry<String, InetAddress> brainInfo = getNeeoBrainInfo(info);
    if (brainInfo == null) {
        logger.debug("BrainInfo null (ignoring): {}", info);
        return;
    }

    logger.debug("NEEO Brain Found: {} (attempt #{} to get information)", brainInfo.getKey(), attempts);

    if (attempts > 120) {
        logger.debug("NEEO Brain found but couldn't retrieve the system information for {} at {} - giving up!",
                brainInfo.getKey(), brainInfo.getValue());
        return;
    }

    NeeoSystemInfo sysInfo;
    try {
        sysInfo = NeeoApi.getSystemInfo(brainInfo.getValue().toString());
    } catch (IOException e) {
        // We can get an MDNS notification BEFORE the brain is ready to process.
        // if that happens, we'll get an IOException (usually bad gateway message), schedule another attempt to get
        // the info (rather than lose the notification)
        scheduler.schedule(() -> {
            considerService(info, attempts + 1);
        }, 1, TimeUnit.SECONDS);
        return;
    }

    systemsLock.lock();
    try {
        final InetAddress oldAddr = systems.get(sysInfo);
        final InetAddress newAddr = brainInfo.getValue();
        if (oldAddr == null) {
            systems.put(sysInfo, newAddr);
            fireDiscovered(sysInfo, newAddr);
            save();
        } else if (!oldAddr.equals(newAddr)) {
            fireRemoved(sysInfo);
            systems.put(sysInfo, newAddr);
            fireUpdated(sysInfo, oldAddr, newAddr);
            save();
        } else {
            logger.debug("NEEO Brain {} already registered", brainInfo.getValue());
        }
    } finally {
        systemsLock.unlock();
    }
}

From source file:org.rhq.core.system.NativeSystemInfo.java

public List<NetConnection> getNetworkConnections(String addressName, int port) {
    try {//from ww w.ja v a 2 s.  c  o  m
        int flags = NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT | NetFlags.CONN_TCP;
        NetConnection[] conns = sigar.getNetConnectionList(flags);

        InetAddress matchAddress = (addressName != null) ? InetAddress.getByName(addressName) : null;

        List<NetConnection> list = new ArrayList<NetConnection>();
        for (NetConnection conn : conns) {
            if (port > 0 && (conn.getLocalPort() != port)) {
                continue; // does not match the port we are looking for
            }
            if (matchAddress != null && !matchAddress.equals(InetAddress.getByName(conn.getLocalAddress()))) {
                continue; // does not match the address we are looking for
            }
            list.add(conn); // matches our criteria, add it to the list to be returned to the caller
        }
        return list;
    } catch (SigarException e) {
        throw new SystemInfoException(e);
    } catch (UnknownHostException e) {
        throw new SystemInfoException(e);
    }
}