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.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java

@SuppressWarnings("unchecked")
public void testSetupPasswordToolAutoSetup() throws Exception {
    final String testConfigDir = System.getProperty("tests.config.dir");
    logger.info("--> CONF: {}", testConfigDir);
    final Path configPath = PathUtils.get(testConfigDir);
    setSystemPropsForTool(configPath);// w  w w . ja va  2 s  .c o m

    Response nodesResponse = client().performRequest("GET", "/_nodes/http");
    Map<String, Object> nodesMap = entityAsMap(nodesResponse);

    Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes");
    Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue();
    Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http");
    String nodePublishAddress = (String) firstNodeHttp.get("publish_address");
    final int lastColonIndex = nodePublishAddress.lastIndexOf(':');
    InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex));
    InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList())
            .resolvePublishHostAddresses(Strings.EMPTY_ARRAY);
    final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1));

    List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml"));
    lines = lines.stream()
            .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false)
            .collect(Collectors.toList());
    lines.add(randomFrom("http.port", "http.publish_port") + ": " + port);
    if (expectedPublishAddress.equals(actualPublishAddress) == false) {
        lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress));
    }
    Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8,
            StandardOpenOption.TRUNCATE_EXISTING);

    MockTerminal mockTerminal = new MockTerminal();
    SetupPasswordTool tool = new SetupPasswordTool();
    final int status;
    if (randomBoolean()) {
        mockTerminal.addTextInput("y"); // answer yes to continue prompt
        status = tool.main(new String[] { "auto" }, mockTerminal);
    } else {
        status = tool.main(new String[] { "auto", "--batch" }, mockTerminal);
    }
    assertEquals(0, status);
    String output = mockTerminal.getOutput();
    logger.info("CLI TOOL OUTPUT:\n{}", output);
    String[] outputLines = output.split("\\n");
    Map<String, String> userPasswordMap = new HashMap<>();
    Arrays.asList(outputLines).forEach(line -> {
        if (line.startsWith("PASSWORD ")) {
            String[] pieces = line.split(" ");
            String user = pieces[1];
            String password = pieces[pieces.length - 1];
            logger.info("user [{}] password [{}]", user, password);
            userPasswordMap.put(user, password);
        }
    });

    assertEquals(4, userPasswordMap.size());
    userPasswordMap.entrySet().forEach(entry -> {
        final String basicHeader = "Basic " + Base64.getEncoder()
                .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8));
        try {
            Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate",
                    new BasicHeader("Authorization", basicHeader));
            assertEquals(200, authenticateResponse.getStatusLine().getStatusCode());
            Map<String, Object> userInfoMap = entityAsMap(authenticateResponse);
            assertEquals(entry.getKey(), userInfoMap.get("username"));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}

From source file:jhttpp2.Jhttpp2ClientInputStream.java

/**
 * Parser for the first (!) line from the HTTP request<BR>
 * Sets up the URL, method and remote hostname.
 * /*  www .  j a  v  a  2 s .c  om*/
 * @return an InetAddress for the hostname, null on errors with a
 *         statuscode!=SC_OK
 */
public InetAddress parseRequest(String a, int method_index) {
    log.debug(a);
    String f;
    int pos;
    url = "";
    if (ssl) {
        f = a.substring(8);
    } else {
        method = a.substring(0, a.indexOf(" ")); // first word in the line
        pos = a.indexOf(":"); // locate first :
        if (pos == -1) { // occours with "GET / HTTP/1.1"
            url = a.substring(a.indexOf(" ") + 1, a.lastIndexOf(" "));
            if (method_index == 0) { // method_index==0 --> GET
                if (url.indexOf(server.WEB_CONFIG_FILE) != -1)
                    statuscode = Jhttpp2HTTPSession.SC_CONFIG_RQ;
                else
                    statuscode = Jhttpp2HTTPSession.SC_FILE_REQUEST;
            } else {
                if (method_index == 1 && url.indexOf(server.WEB_CONFIG_FILE) != -1) { // allow
                    // "POST"
                    // for
                    // admin
                    // log
                    // in
                    statuscode = Jhttpp2HTTPSession.SC_CONFIG_RQ;
                } else {
                    statuscode = Jhttpp2HTTPSession.SC_INTERNAL_SERVER_ERROR;
                    errordescription = "This WWW proxy supports only the \"GET\" method while acting as webserver.";
                }
            }
            return null;
        }
        f = a.substring(pos + 3); // removes "http://"
    }
    pos = f.indexOf(" "); // locate space, should be the space before
    // "HTTP/1.1"
    if (pos == -1) { // buggy request
        statuscode = Jhttpp2HTTPSession.SC_CLIENT_ERROR;
        errordescription = "Your browser sent an invalid request: \"" + a + "\"";
        return null;
    }
    f = f.substring(0, pos); // removes all after space
    // if the url contains a space... it's not our mistake...(url's must
    // never contain a space character)
    pos = f.indexOf("/"); // locate the first slash
    if (pos != -1) {
        url = f.substring(pos); // saves path without hostname
        f = f.substring(0, pos); // reduce string to the hostname
    } else
        url = "/"; // occurs with this request:
    // "GET http://localhost HTTP/1.1"
    pos = f.indexOf(":"); // check for the portnumber
    if (pos != -1) {
        String l_port = f.substring(pos + 1);
        l_port = l_port.indexOf(" ") != -1 ? l_port.substring(0, l_port.indexOf(" ")) : l_port;
        int i_port = 80;
        try {
            i_port = Integer.parseInt(l_port);
        } catch (NumberFormatException e_get_host) {
            server.writeLog("get_Host :" + e_get_host + " !!!!");
        }
        f = f.substring(0, pos);
        remote_port = i_port;
    } else
        remote_port = 80;
    remote_host_name = f;

    SortedMap<String, URL> map = server.getHostRedirects();
    for (String redirectHost : map.keySet()) {
        if (redirectHost.equals(remote_host_name)) {
            URL u = map.get(redirectHost);
            f = u.getHost();
            if (u.getPort() != -1) {
                remote_port = u.getPort();
            }
            log.debug("Redirecting host " + redirectHost + " to " + f + " port " + remote_port);
        }
    }
    InetAddress address = null;
    if (server.log_access)
        server.logAccess(connection.getLocalSocket().getInetAddress().getHostAddress() + " " + method + " "
                + getFullURL());
    try {
        address = InetAddress.getByName(f);
        if (remote_port == server.port && address.equals(InetAddress.getLocalHost())) {
            if (url.indexOf(server.WEB_CONFIG_FILE) != -1 && (method_index == 0 || method_index == 1))
                statuscode = Jhttpp2HTTPSession.SC_CONFIG_RQ;
            else if (method_index > 0) {
                statuscode = Jhttpp2HTTPSession.SC_INTERNAL_SERVER_ERROR;
                errordescription = "This WWW proxy supports only the \"GET\" method while acting as webserver.";
            } else
                statuscode = Jhttpp2HTTPSession.SC_FILE_REQUEST;
        }
    } catch (UnknownHostException e_u_host) {
        if (!server.use_proxy)
            statuscode = Jhttpp2HTTPSession.SC_HOST_NOT_FOUND;
    }
    return address;
}

From source file:org.apache.cassandra.hadoop.ColumnFamilyRecordReader.java

private String getLocation() {
    ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
    try {/*from w w  w.  j  a v  a 2  s . c  o m*/
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        while (nets.hasMoreElements())
            localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses()));
    } catch (SocketException e) {
        throw new AssertionError(e);
    }

    for (InetAddress address : localAddresses) {
        for (String location : split.getLocations()) {
            InetAddress locationAddress = null;
            try {
                locationAddress = InetAddress.getByName(location);
            } catch (UnknownHostException e) {
                throw new AssertionError(e);
            }
            if (address.equals(locationAddress)) {
                return location;
            }
        }
    }
    return split.getLocations()[0];
}

From source file:org.limewire.mojito.routing.impl.LocalContact.java

/**
 * Sets the external Address of the local Node.
 *///from   ww w  . j  a  va2 s  . c om
public synchronized boolean setExternalAddress(SocketAddress externalSocketAddress) {
    if (externalSocketAddress == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SocketAddress is null");
        }
        return false;
    }

    // --- DOES NOT CHANGE THE PORT! ---

    InetAddress externalAddress = ((InetSocketAddress) externalSocketAddress).getAddress();
    //int externalPort = ((InetSocketAddress)externalSocketAddress).getPort();

    InetAddress currentAddress = ((InetSocketAddress) getContactAddress()).getAddress();
    int currentPort = ((InetSocketAddress) getContactAddress()).getPort();

    if (externalAddress.equals(currentAddress)) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Reported external address is equal to current external address: " + externalAddress);
        }
        return false;
    }

    // There's no reason to set the external address to a
    // PRIVATE IP address. This can happen with a Node that
    // is pinging an another Node that is behind the same
    // NAT router
    if (ContactUtils.isPrivateAddress(externalAddress)) {
        if (LOG.isInfoEnabled()) {
            LOG.info(externalAddress + " is a PRIVATE address");
        }
        return false;
    }

    if (!NetworkUtils.isSameAddressSpace(externalAddress, currentAddress)) {

        // The remote Node tries to set our external address
        // to an address that's from a different address space?
        if (LOG.isWarnEnabled()) {
            LOG.warn("The current external address " + currentAddress
                    + " is from a different IP address space than " + externalAddress);
        }
        return false;
    }

    SocketAddress addr = new InetSocketAddress(externalAddress, currentPort);

    if (tmpExternalAddress == null || tmpExternalAddress.equals(addr)) {

        if (LOG.isInfoEnabled()) {
            LOG.info("Setting the current external address from " + contactAddress + " to " + addr);
        }

        contactAddress = addr;

        //if (externalPort == currentPort) {}
    }

    tmpExternalAddress = addr;
    return true;
}

From source file:org.opendaylight.controller.web.DaylightWebAdmin.java

/**
 * Returns list of clustered controllers. Highlights "this" controller and
 * if controller is coordinator/*ww w  .  j a  va 2s  . com*/
 *
 * @return List<ClusterBean>
 */
@RequestMapping("/cluster")
@ResponseBody
public String getClusteredControllers() {
    IClusterGlobalServices clusterServices = (IClusterGlobalServices) ServiceHelper
            .getGlobalInstance(IClusterGlobalServices.class, this);
    if (clusterServices == null) {
        return null;
    }
    IConnectionManager connectionManager = (IConnectionManager) ServiceHelper
            .getGlobalInstance(IConnectionManager.class, this);
    if (connectionManager == null) {
        return null;
    }

    List<ClusterNodeBean> clusterNodes = new ArrayList<ClusterNodeBean>();

    List<InetAddress> controllers = clusterServices.getClusteredControllers();
    for (InetAddress controller : controllers) {
        ClusterNodeBean.Builder clusterBeanBuilder = new ClusterNodeBean.Builder(controller);

        // get number of connected nodes
        Set<Node> connectedNodes = connectionManager.getNodes(controller);
        int numNodes = connectedNodes == null ? 0 : connectedNodes.size();
        clusterBeanBuilder.nodesConnected(numNodes);

        // determine if this is the executing controller
        if (controller.equals(clusterServices.getMyAddress())) {
            clusterBeanBuilder.highlightMe();
        }

        // determine whether this is coordinator
        if (clusterServices.getCoordinatorAddress().equals(controller)) {
            clusterBeanBuilder.iAmCoordinator();
        }
        clusterNodes.add(clusterBeanBuilder.build());
    }

    return gson.toJson(clusterNodes);
}

From source file:com.netxforge.oss2.config.SnmpPeerFactory.java

private SnmpAgentConfig getAgentConfig(final InetAddress agentInetAddress, final int requestedSnmpVersion) {
    SnmpPeerFactory.getReadLock().lock();
    try {/*from  w  w  w  .j  a v a2 s . c  o  m*/
        if (m_config == null) {
            final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress);
            if (requestedSnmpVersion == VERSION_UNSPECIFIED) {
                agentConfig.setVersion(SnmpAgentConfig.DEFAULT_VERSION);
            } else {
                agentConfig.setVersion(requestedSnmpVersion);
            }

            return agentConfig;
        }

        final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress);

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

        // Attempt to locate the node
        DEFLOOP: for (final Definition def : m_config.getDefinitionCollection()) {
            // check the specifics first
            for (final String saddr : def.getSpecificCollection()) {
                try {
                    final InetAddress addr = InetAddressUtils.addr(saddr);
                    if (addr != null && addr.equals(agentConfig.getAddress())) {
                        setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                        break DEFLOOP;
                    }
                } catch (final IllegalArgumentException e) {
                    LogUtils.debugf(this, e, "Error while reading SNMP config <specific> tag: %s", saddr);
                }
            }

            // check the ranges
            //
            final ByteArrayComparator comparator = new ByteArrayComparator();

            for (final Range rng : def.getRangeCollection()) {
                final byte[] addr = agentConfig.getAddress().getAddress();
                final byte[] begin = InetAddressUtils.toIpAddrBytes(rng.getBegin());
                final byte[] end = InetAddressUtils.toIpAddrBytes(rng.getEnd());

                boolean inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end);
                if (comparator.compare(begin, end) <= 0) {
                    inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end);
                } else {
                    LogUtils.warnf(this, "%s has an 'end' that is earlier than its 'beginning'!", rng);
                    inRange = InetAddressUtils.isInetAddressInRange(addr, end, begin);
                }
                if (inRange) {
                    setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                    break DEFLOOP;
                }
            }

            // check the matching ip expressions
            for (final String ipMatch : def.getIpMatchCollection()) {
                if (IPLike.matches(agentInetAddress, ipMatch)) {
                    setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                    break DEFLOOP;
                }
            }

        } // end DEFLOOP

        if (agentConfig == null) {
            final Definition def = new Definition();
            setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
        }

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

From source file:com.atomicleopard.thundr.ftp.commons.SocketClient.java

/**
 * Verifies that the remote end of the given socket is connected to the
 * the same host that the SocketClient is currently connected to.  This
 * is useful for doing a quick security check when a client needs to
 * accept a connection from a server, such as an FTP data connection or
 * a BSD R command standard error stream.
 * <p>/*from   w  w  w . ja  va 2  s  . c  om*/
 * @return True if the remote hosts are the same, false if not.
 */
public boolean verifyRemote(Socket socket) {
    InetAddress host1, host2;

    host1 = socket.getInetAddress();
    host2 = getRemoteAddress();

    return host1.equals(host2);
}

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

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

    lock.writeLock().lock();//from w  ww  . j  av  a  2 s. co  m
    try {
        bootstrapTokens.inverse().remove(endpoint);
        tokenToEndpointMap.inverse().remove(endpoint);
        InetAddress prev = tokenToEndpointMap.put(token, endpoint);
        if (!endpoint.equals(prev)) {
            if (prev != null)
                logger.warn("Token " + token + " changing ownership from " + prev + " to " + endpoint);
            sortedTokens = sortTokens();
        }
        leavingEndpoints.remove(endpoint);
        removeFromMoving(endpoint); // also removing this endpoint from moving
        invalidateCaches();
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.opennms.ng.services.snmpconfig.SnmpPeerFactory.java

private SnmpAgentConfig getAgentConfig(final InetAddress agentInetAddress, final int requestedSnmpVersion) {
    SnmpPeerFactory.getReadLock().lock();
    try {/*from www  .  j  av a 2 s.c om*/
        if (m_config == null) {
            final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress);
            if (requestedSnmpVersion == VERSION_UNSPECIFIED) {
                agentConfig.setVersion(SnmpAgentConfig.DEFAULT_VERSION);
            } else {
                agentConfig.setVersion(requestedSnmpVersion);
            }

            return agentConfig;
        }

        final SnmpAgentConfig agentConfig = new SnmpAgentConfig(agentInetAddress);

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

        // Attempt to locate the node
        DEFLOOP: for (final Definition def : m_config.getDefinitionCollection()) {
            // check the specifics first
            for (final String saddr : def.getSpecificCollection()) {
                try {
                    final InetAddress addr = InetAddressUtils.addr(saddr);
                    if (addr != null && addr.equals(agentConfig.getAddress())) {
                        setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                        break DEFLOOP;
                    }
                } catch (final IllegalArgumentException e) {
                    LOG.debug("Error while reading SNMP config <specific> tag: {}", saddr, e);
                }
            }

            // check the ranges
            //
            final ByteArrayComparator comparator = new ByteArrayComparator();

            for (final Range rng : def.getRangeCollection()) {
                final byte[] addr = agentConfig.getAddress().getAddress();
                final byte[] begin = InetAddressUtils.toIpAddrBytes(rng.getBegin());
                final byte[] end = InetAddressUtils.toIpAddrBytes(rng.getEnd());

                boolean inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end);
                if (comparator.compare(begin, end) <= 0) {
                    inRange = InetAddressUtils.isInetAddressInRange(addr, begin, end);
                } else {
                    LOG.warn("{} has an 'end' that is earlier than its 'beginning'!", rng);
                    inRange = InetAddressUtils.isInetAddressInRange(addr, end, begin);
                }
                if (inRange) {
                    setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                    break DEFLOOP;
                }
            }

            // check the matching ip expressions
            for (final String ipMatch : def.getIpMatchCollection()) {
                if (IPLike.matches(agentInetAddress, ipMatch)) {
                    setSnmpAgentConfig(agentConfig, def, requestedSnmpVersion);
                    break DEFLOOP;
                }
            }

        } // end DEFLOOP
        return agentConfig;
    } finally {
        SnmpPeerFactory.getReadLock().unlock();
    }
}

From source file:org.jsecurity.web.session.DefaultWebSessionManager.java

protected void validateSessionOrigin(ServletRequest request, Session session) throws HostUnauthorizedException {
    InetAddress requestIp = WebUtils.getInetAddress(request);
    InetAddress originIp = session.getHostAddress();
    Serializable sessionId = session.getId();

    if (originIp == null) {
        if (requestIp != null) {
            String msg = "No IP Address was specified when creating session with id [" + sessionId
                    + "].  Attempting to access session from " + "IP [" + requestIp
                    + "].  Origin IP and request IP must match.";
            throw new HostUnauthorizedException(msg);
        }/*from ww w . jav a  2 s.  c  o m*/
    } else {
        if (requestIp != null) {
            if (!requestIp.equals(originIp)) {
                String msg = "Session with id [" + sessionId + "] originated from [" + originIp
                        + "], but the current HttpServletRequest originated " + "from [" + requestIp
                        + "].  Disallowing session access: "
                        + "session origin and request origin must match to allow access.";
                throw new HostUnauthorizedException(msg);
            }

        } else {
            String msg = "No IP Address associated with the current HttpServletRequest.  " + "Session with id ["
                    + sessionId + "] originated from " + "[" + originIp
                    + "].  Request IP must match the session's origin "
                    + "IP in order to gain access to that session.";
            throw new HostUnauthorizedException(msg);
        }
    }
}