Java Host Address Get getHostAddress(String hostPort)

Here you can find the source of getHostAddress(String hostPort)

Description

Gets the host name from a host:port.

License

Open Source License

Parameter

Parameter Description
hostPort The host:port in "host:port", "host" or ":port" syntax.

Exception

Parameter Description
UnknownHostException If the host name is invalid.

Return

The applicable host name or null if not specified.

Declaration

public static InetAddress getHostAddress(String hostPort) throws UnknownHostException 

Method Source Code

//package com.java2s;
/**//from  w  w w. j a va 2  s.co  m
 * This file is protected by Copyright. Please refer to the COPYRIGHT file
 * distributed with this source distribution.
 *
 * This file is part of REDHAWK.
 *
 * REDHAWK is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * REDHAWK is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 */

import java.net.InetAddress;

import java.net.UnknownHostException;

public class Main {
    /**  Gets the host name from a host:port.
    @param hostPort The host:port in "host:port", "host" or ":port" syntax.
    @return The applicable host name or null if not specified.
    @throws UnknownHostException If the host name is invalid.
     */
    public static InetAddress getHostAddress(String hostPort) throws UnknownHostException {
        String host = getHost(hostPort);
        return (host == null) ? null : InetAddress.getByName(host);
    }

    /**  Gets the host name from a host:port.
    @param hostPort The host:port in "host:port", "host" or ":port" syntax.
    @return The applicable host name or null if not specified.
     */
    public static String getHost(String hostPort) {
        if (hostPort.startsWith("[")) {
            // IPv6 address
            int i = hostPort.indexOf("]");
            return hostPort.substring(1, i);
        }
        int i = hostPort.lastIndexOf(':');
        if (i < 0)
            return hostPort; // no port, just a host name
        if (i == 0)
            return null; // no host, just a port number
        return hostPort.substring(0, i);
    }
}

Related

  1. getHostAddress()
  2. getHostAddress()
  3. getHostAddress(boolean promiscuous)
  4. getHostAddress(final String name)
  5. getHostAddress(String hostname)
  6. getHostAddresses()
  7. getHostAddresses()
  8. getHostAddresses()
  9. getHostAddressFromProperty(final String property)