Java URI to Host Name getHostAddress(final URI uri)

Here you can find the source of getHostAddress(final URI uri)

Description

Get the address of the host.

License

Open Source License

Parameter

Parameter Description
uri a parameter

Return

The InetAddress of the host specified in the URI. Will return null if DNS lookup fails, if the URI reference is null or if no host is specified in the URI.

Declaration

public static InetAddress getHostAddress(final URI uri) 

Method Source Code

//package com.java2s;
/*//from  w w  w .  j a va 2 s . c  o m
 * Copyright (c) 2014 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial concept and implementation
 */

import java.net.InetAddress;

import java.net.URI;

public class Main {
    /**
     * Get the address of the host.
     *
     * <p><b>NOTE</b>: This may take a long time as it will perform a DNS lookup
     * which can take several seconds!</p>
     *
     *
     * @param uri
     *
     * @return The InetAddress of the host specified in the URI. Will return null
     *         if DNS lookup fails, if the URI reference is null or if no host is
     *         specified in the URI.
     */
    public static InetAddress getHostAddress(final URI uri) {
        if (uri != null) {
            final String host = uri.getHost();

            if (host != null) {
                try {
                    return InetAddress.getByName(host);
                } catch (final Exception exception) {
                }
            }
        }

        return null;
    }

    /**
     * Return just the host portion of the URI if applicable.
     *
     * @param uri The URI to parse
     * 
     * @return The host portion of the authority.
     */
    public static String getHost(final URI uri) {
        String retval = uri.getHost();

        // The most common reason for getHost failure is that a port was not
        // defined in the URI making it hard for the URI class to figure out which
        // part of the authority is the host portion. We assume anything infront of
        // the colon is the host.
        if ((retval == null) && (uri.getAuthority() != null)) {
            // The authority is usually in the form of XXXX:999 as in "myhost:-1"
            final String text = uri.getAuthority();
            final int ptr = text.indexOf(':');

            if (ptr > -1) {
                // just return the host portion
                retval = text.substring(0, ptr);
            }
        }

        return retval;
    }
}

Related

  1. getHost(final URI uri)
  2. getHost(URI uri)
  3. getHost(URI uri)
  4. getHost(URI uri)
  5. getHostAddress(final URI uri)
  6. getHostAndPort(URI u)
  7. getHostFromURI(final URI uri)
  8. getHostUri()