Example usage for java.net InetAddress getHostAddress

List of usage examples for java.net InetAddress getHostAddress

Introduction

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

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation.

Usage

From source file:com.adaptris.sftp.SftpClient.java

/**
 * Constructor./*  w  ww. j  a va 2 s . c om*/
 *
 * @param addr the remote ssh host.
 * @param port the ssh port.
 * @param timeout the timeout;
 */
public SftpClient(InetAddress addr, int port, int timeout) throws SftpException {
    this(addr.getHostAddress(), port, timeout, null, null);
}

From source file:edu.vt.middleware.gator.log4j.SocketServer.java

/**
 * Gets the logging event handler for the given client.
 * /*w w  w .j  av  a2s .  co m*/
 * @param  hostNameOrIp  Host name or IP address of client.
 *
 * @return  Logging event handler for given client or null if no handler is
 * found for given client.
 */
public LoggingEventHandler getLoggingEventHandler(final String hostNameOrIp) {
    for (InetAddress address : eventHandlerMap.keySet()) {
        if (address.getHostName().equals(hostNameOrIp) || address.getHostAddress().equals(hostNameOrIp)) {
            return eventHandlerMap.get(address);
        }
    }
    return null;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

/**
 * Sets up a connection, retrying on connect failure.
 *//*from  w ww . j  av  a 2 s  . c om*/
private HttpURLConnection connect(final URI uri, final String method, final byte[] entity,
        final Map<String, List<String>> headers)
        throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException {
    final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS;
    final int offset = ThreadLocalRandom.current().nextInt();

    while (currentTimeMillis() < deadline) {
        final List<URI> endpoints = endpointSupplier.get();
        if (endpoints.isEmpty()) {
            throw new RuntimeException("failed to resolve master");
        }
        log.debug("endpoint uris are {}", endpoints);

        // Resolve hostname into IPs so client will round-robin and retry for multiple A records.
        // Keep a mapping of IPs to hostnames for TLS verification.
        final List<URI> ipEndpoints = Lists.newArrayList();
        final Map<URI, URI> ipToHostnameUris = Maps.newHashMap();

        for (final URI hnUri : endpoints) {
            try {
                final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost());
                for (final InetAddress ip : ips) {
                    final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(),
                            hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment());
                    ipEndpoints.add(ipUri);
                    ipToHostnameUris.put(ipUri, hnUri);
                }
            } catch (UnknownHostException e) {
                log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e);
            }
        }

        for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) {
            final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size());
            final String fullpath = ipEndpoint.getPath() + uri.getPath();

            final String scheme = ipEndpoint.getScheme();
            final String host = ipEndpoint.getHost();
            final int port = ipEndpoint.getPort();
            if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) {
                throw new HeliosException(String.format(
                        "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"",
                        VALID_PROTOCOLS_STR));
            }

            final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null);

            AgentProxy agentProxy = null;
            Deque<Identity> identities = Queues.newArrayDeque();
            try {
                if (scheme.equals("https")) {
                    agentProxy = AgentProxies.newInstance();
                    for (final Identity identity : agentProxy.list()) {
                        if (identity.getPublicKey().getAlgorithm().equals("RSA")) {
                            // only RSA keys will work with our TLS implementation
                            identities.offerLast(identity);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("Couldn't get identities from ssh-agent", e);
            }

            try {
                do {
                    final Identity identity = identities.poll();

                    try {
                        log.debug("connecting to {}", realUri);

                        final HttpURLConnection connection = connect0(realUri, method, entity, headers,
                                ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity);

                        final int responseCode = connection.getResponseCode();
                        if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED))
                                && !identities.isEmpty()) {
                            // there was some sort of security error. if we have any more SSH identities to try,
                            // retry with the next available identity
                            log.debug("retrying with next SSH identity since {} failed", identity.getComment());
                            continue;
                        }

                        return connection;
                    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
                        // UnknownHostException happens if we can't resolve hostname into IP address.
                        // UnknownHostException's getMessage method returns just the hostname which is a
                        // useless message, so log the exception class name to provide more info.
                        log.debug(e.toString());
                        // Connecting failed, sleep a bit to avoid hammering and then try another endpoint
                        Thread.sleep(200);
                    }
                } while (false);
            } finally {
                if (agentProxy != null) {
                    agentProxy.close();
                }
            }
        }
        log.warn("Failed to connect, retrying in 5 seconds.");
        Thread.sleep(5000);
    }
    throw new TimeoutException("Timed out connecting to master");
}

From source file:interactivespaces.system.bootstrap.osgi.GeneralInteractiveSpacesSupportActivator.java

/**
 * Convert the given hostname to an IP address.
 *
 * @param hostname/* w ww.j a v a  2s . c o m*/
 *          hostname to convert
 *
 * @return host IP address
 */
private String convertHostnameToAddress(String hostname) {
    try {
        InetAddress address = InetAddress.getByName(hostname);
        return address.getHostAddress();
    } catch (Exception e) {
        spaceEnvironment.getLog().error("Could not convert hostname to IP address", e);
        return UNKNOWN_HOST_ADDRESS;
    }
}

From source file:edu.ucsd.crbs.cws.auth.UserIpAddressValidatorImpl.java

/**
 * Compares <b>requestAddress</b> against ipv6 cidr in <b>cidrAddress</b>
 * @param requestAddress ipv6 address of the request
 * @param cidrAddress ipv6 CIDR address//from   ww w  .j a va2  s. c  o m
 * @return true if the <b>requestAddress</b> is within the range of the 
 * <b>cidrAddress</b>, false otherwise
 */
private boolean isIpv6AddressInCidrAddress(InetAddress requestAddress, final String cidrAddress) {
    try {
        IPv6Network network = IPv6Network.fromString(cidrAddress);
        return network.contains(IPv6Address.fromInetAddress(requestAddress));
    } catch (Exception ex) {
        _log.log(Level.WARNING, "Problems parsing cidr address: {0} and comparing to {1} : {2}",
                new Object[] { cidrAddress, requestAddress.getHostAddress(), ex.getMessage() });
    }
    return false;
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

@SuppressWarnings("unchecked")
private void addIps(JSONObject values) {
    List<String> ip4s = new ArrayList<>();
    List<String> ip6s = new ArrayList<>();
    String ip = "unknown";
    try {/*from  ww w .  j a va2s. c  om*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress address = inetAddresses.nextElement();
                if (address instanceof Inet4Address) {
                    ip4s.add(address.getHostAddress() + "_" + address.getHostName());
                    if (!address.isLinkLocalAddress() && !address.isAnyLocalAddress()
                            && !address.isLoopbackAddress()) {
                        ip = address.getHostAddress();
                    }
                }
                if (address instanceof Inet6Address) {
                    ip6s.add(address.getHostAddress() + "_" + address.getHostName());
                }
            }
        }
        ip4s.add("LOC_" + InetAddress.getLocalHost().getHostAddress() + "_"
                + InetAddress.getLocalHost().getHostName());
        if (!ip4s.isEmpty()) {
            values.put("ip", ip);
            values.put("ip4s", ip4s);
        }
        if (!ip6s.isEmpty()) {
            values.put("ip6s", ip6s);
        }
    } catch (UnknownHostException | SocketException e) {
        values.put("ip", "offline_" + e.getMessage());
    }
}

From source file:com.yodlee.sampleapps.helper.OpenSamlHelper.java

/**
 * This function generates the response.
 *
 * @param subjects/*from   ww w.  j  a v  a 2  s  .  c  om*/
 * @return SAMLResponse object
 * @throws SAMLException
 * @throws Exception
 */
public SAMLResponse generateResponse(String[] subjects, String issuer) throws SAMLException {
    // Get Host Information
    InetAddress address = null;
    try {
        address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
    String IPAddress = address.getHostAddress();
    String DNSAddress = address.getHostName();

    Collection statements = new ArrayList();

    // Create the SAML subject
    for (int i = 0; i < subjects.length; i++) {
        String subject = subjects[i];
        SAMLNameIdentifier nameIdentifier = new SAMLNameIdentifier(subject, null,
                SAMLNameIdentifier.FORMAT_X509);
        List confirmationMethodList = new ArrayList();
        confirmationMethodList.add(SAMLSubject.CONF_BEARER);

        SAMLSubject samlSubject = new SAMLSubject(nameIdentifier, confirmationMethodList, null, null);

        // Create the SAML Authentication Statement
        SAMLAuthenticationStatement sas = new SAMLAuthenticationStatement
        //(subject,"auth",new Date(),IPAddress,DNSAddress,null);
        (samlSubject, "password", new Date(), IPAddress, DNSAddress, null);

        statements.add(sas);
    }

    // Create the SAML Assertion
    SAMLAssertion assertion = new SAMLAssertion
    //(issuer,new Date(),new Date(),null,null,statements);
    (issuer, null, null, null, null, statements);
    Collection assertions = new ArrayList();
    assertions.add(assertion);

    // Create the SAML Response
    SAMLResponse response = null;
    response = new SAMLResponse("artifact", subjects[0], assertions, null);

    Collection dsa_certs = new ArrayList();
    for (int i = 0; i < OpenSamlHelper.certs.length; i++)
        dsa_certs.add(OpenSamlHelper.certs[i]);

    // Sign the Response
    try {
        response.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA, OpenSamlHelper.privateKey, dsa_certs);
    } catch (SAMLException e) {
        System.out.println("SAMLException.  Error signing the response.");
        e.printStackTrace();
    }
    //response.toStream( System.out);

    return response;
}

From source file:com.sshtools.j2ssh.agent.SshAgentClient.java

/**
 * Send a forwarding notice.//from  w w  w  .jav a2s  . c  om
 *
 * @throws IOException if an IO error occurs
 */
protected void sendForwardingNotice() throws IOException {
    InetAddress addr = InetAddress.getLocalHost();

    SshAgentForwardingNotice msg = new SshAgentForwardingNotice(addr.getHostName(), addr.getHostAddress(), 22);

    sendMessage(msg);
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public String getLocalIpAddress() {
    try {/* w  w w  .j  a v a  2s  .c  o m*/
        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()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("", ex.toString());
    }
    return null;
}

From source file:net.pms.network.RequestHandler.java

@Override
public void run() {
    Request request = null;//from  ww w . j av a2  s. c  o  m
    StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(
            socket.getInetAddress().getHostAddress());

    try {
        int receivedContentLength = -1;
        String userAgentString = null;
        ArrayList<String> identifiers = new ArrayList<>();
        RendererConfiguration renderer = null;

        InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
        InetAddress ia = remoteAddress.getAddress();

        boolean isSelf = ia.getHostAddress().equals(PMS.get().getServer().getHost());

        // Apply the IP filter
        if (filterIp(ia)) {
            throw new IOException("Access denied for address " + ia + " based on IP filter");
        }

        LOGGER.trace("Opened request handler on socket " + socket);
        PMS.get().getRegistry().disableGoToSleep();

        // The handler makes a couple of attempts to recognize a renderer from its requests.
        // IP address matches from previous requests are preferred, when that fails request
        // header matches are attempted and if those fail as well we're stuck with the
        // default renderer.

        // Attempt 1: try to recognize the renderer by its socket address from previous requests
        renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);

        // If the renderer exists but isn't marked as loaded it means it's unrecognized
        // by upnp and we still need to attempt http recognition here.
        boolean unrecognized = renderer == null || !renderer.loaded;
        RendererConfiguration.SortedHeaderMap sortedHeaders = unrecognized
                ? new RendererConfiguration.SortedHeaderMap()
                : null;

        // Gather all the headers
        ArrayList<String> headerLines = new ArrayList<>();
        String line = br.readLine();
        while (line != null && line.length() > 0) {
            headerLines.add(line);
            if (unrecognized) {
                sortedHeaders.put(line);
            }
            line = br.readLine();
        }

        if (unrecognized) {
            // Attempt 2: try to recognize the renderer by matching headers
            renderer = RendererConfiguration.getRendererConfigurationByHeaders(sortedHeaders, ia);
        }

        for (String headerLine : headerLines) {
            LOGGER.trace("Received on socket: " + headerLine);

            // The request object is created inside the while loop.
            if (request != null && request.getMediaRenderer() == null && renderer != null) {
                request.setMediaRenderer(renderer);
            }
            if (headerLine.toUpperCase().startsWith("USER-AGENT")) {
                // Is the request from our own Cling service, i.e. self-originating?
                if (isSelf && headerLine.contains("UMS/")) {
                    LOGGER.trace(
                            "Ignoring self-originating request from " + ia + ":" + remoteAddress.getPort());
                    return;
                }
                userAgentString = headerLine.substring(headerLine.indexOf(':') + 1).trim();
            }

            try {
                StringTokenizer s = new StringTokenizer(headerLine);
                String temp = s.nextToken();
                if (temp.equals("SUBSCRIBE") || temp.equals("GET") || temp.equals("POST")
                        || temp.equals("HEAD")) {
                    request = new Request(temp, s.nextToken().substring(1));
                    if (s.hasMoreTokens() && s.nextToken().equals("HTTP/1.0")) {
                        request.setHttp10(true);
                    }
                } else if (request != null && temp.toUpperCase().equals("CALLBACK:")) {
                    request.setSoapaction(s.nextToken());
                } else if (request != null && temp.toUpperCase().equals("SOAPACTION:")) {
                    request.setSoapaction(s.nextToken());
                } else if (headerLine.toUpperCase().contains("CONTENT-LENGTH:")) {
                    receivedContentLength = Integer.parseInt(
                            headerLine.substring(headerLine.toUpperCase().indexOf("CONTENT-LENGTH: ") + 16));
                } else if (headerLine.toUpperCase().contains("RANGE: BYTES=")) {
                    String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13)
                            .trim();
                    StringTokenizer st = new StringTokenizer(nums, "-");
                    if (!nums.startsWith("-")) {
                        request.setLowRange(Long.parseLong(st.nextToken()));
                    }
                    if (!nums.startsWith("-") && !nums.endsWith("-")) {
                        request.setHighRange(Long.parseLong(st.nextToken()));
                    } else {
                        request.setHighRange(-1);
                    }
                } else if (headerLine.toLowerCase().contains("transfermode.dlna.org:")) {
                    request.setTransferMode(headerLine
                            .substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
                } else if (headerLine.toLowerCase().contains("getcontentfeatures.dlna.org:")) {
                    request.setContentFeatures(headerLine
                            .substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28)
                            .trim());
                } else if (headerLine.toUpperCase().contains("TIMESEEKRANGE.DLNA.ORG: NPT=")) { // firmware 2.50+
                    String timeseek = headerLine
                            .substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") + 28);
                    if (timeseek.endsWith("-")) {
                        timeseek = timeseek.substring(0, timeseek.length() - 1);
                    } else if (timeseek.indexOf('-') > -1) {
                        timeseek = timeseek.substring(0, timeseek.indexOf('-'));
                    }
                    request.setTimeseek(convertStringToTime(timeseek));
                } else if (headerLine.toUpperCase().contains("TIMESEEKRANGE.DLNA.ORG : NPT=")) { // firmware 2.40
                    String timeseek = headerLine
                            .substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") + 29);
                    if (timeseek.endsWith("-")) {
                        timeseek = timeseek.substring(0, timeseek.length() - 1);
                    } else if (timeseek.indexOf('-') > -1) {
                        timeseek = timeseek.substring(0, timeseek.indexOf('-'));
                    }
                    request.setTimeseek(convertStringToTime(timeseek));
                } else {
                    /*
                     * If we made it to here, none of the previous header checks matched.
                     * Unknown headers make interesting logging info when we cannot recognize
                     * the media renderer, so keep track of the truly unknown ones.
                     */
                    boolean isKnown = false;

                    // Try to match possible known headers.
                    String lowerCaseHeaderLine = headerLine.toLowerCase();
                    for (String knownHeaderString : KNOWN_HEADERS) {
                        if (lowerCaseHeaderLine.startsWith(knownHeaderString.toLowerCase())) {
                            isKnown = true;
                            break;
                        }
                    }

                    // It may be unusual but already known
                    if (renderer != null) {
                        String additionalHeader = renderer.getUserAgentAdditionalHttpHeader();
                        if (StringUtils.isNotBlank(additionalHeader)
                                && lowerCaseHeaderLine.startsWith(additionalHeader)) {
                            isKnown = true;
                        }
                    }

                    if (!isKnown) {
                        // Truly unknown header, therefore interesting. Save for later use.
                        identifiers.add(headerLine);
                    }
                }
            } catch (IllegalArgumentException e) {
                LOGGER.error("Error in parsing HTTP headers", e);
            }
        }

        if (request != null) {
            // Still no media renderer recognized?
            if (renderer == null) {
                // Attempt 3: Not really an attempt; all other attempts to recognize
                // the renderer have failed. The only option left is to assume the
                // default renderer.
                renderer = RendererConfiguration.resolve(ia, null);
                request.setMediaRenderer(renderer);
                if (renderer != null) {
                    LOGGER.trace("Using default media renderer: " + renderer.getConfName());

                    if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
                        // We have found an unknown renderer
                        identifiers.add(0, "User-Agent: " + userAgentString);
                        renderer.setIdentifiers(identifiers);
                        LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers:"
                                + StringUtils.join(identifiers, ", "));
                    }
                } else {
                    // If RendererConfiguration.resolve() didn't return the default renderer
                    // it means we know via upnp that it's not really a renderer.
                    return;
                }
            } else {
                if (userAgentString != null) {
                    LOGGER.trace("HTTP User-Agent: " + userAgentString);
                }
                LOGGER.trace("Recognized media renderer: " + renderer.getRendererName());
            }
        }

        if (receivedContentLength > 0) {
            char buf[] = new char[receivedContentLength];
            br.read(buf);
            if (request != null) {
                request.setTextContent(new String(buf));
            }
        }

        if (request != null) {
            LOGGER.trace("HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-"
                    + request.getHighRange());
        }

        if (request != null) {
            request.answer(output, startStopListenerDelegate);
        }

        if (request != null && request.getInputStream() != null) {
            request.getInputStream().close();
        }
    } catch (IOException e) {
        LOGGER.trace("Unexpected IO error: " + e.getClass().getName() + ": " + e.getMessage());
        if (request != null && request.getInputStream() != null) {
            try {
                LOGGER.trace("Closing input stream: " + request.getInputStream());
                request.getInputStream().close();
            } catch (IOException e1) {
                LOGGER.error("Error closing input stream", e1);
            }
        }
    } finally {
        try {
            PMS.get().getRegistry().reenableGoToSleep();
            output.close();
            br.close();
            socket.close();
        } catch (IOException e) {
            LOGGER.error("Error closing connection: ", e);
        }

        startStopListenerDelegate.stop();
        LOGGER.trace("Close connection");
    }
}