Java Utililty Methods URL to Host Name

List of utility methods to do URL to Host Name

Description

The list of methods to do URL to Host Name are organized into topic(s).

Method

String[]getHostAndPortFromUrl(String url)
Parse the string as a URL and extract the host name from it.
int size = url.length();
char[] url_chars = url.toCharArray();
String scheme = getScheme(url_chars);
if (protocol_ports.get(scheme) == null)
    return null;
int start_pos, end_pos;
int start_hostname, end_hostname;
int start_port, end_port;
...
StringgetHostFromURL(final String urlSpec)
get Host From URL
if (urlSpec == null) {
    return null;
try {
    final URL url = new URL(urlSpec);
    final String host = url.getHost();
    final int port = url.getPort();
    if (port == -1) {
...
StringgetHostname(String completeUrl)
This method will parse the passed in String which is presumably a complete URL and return the base URL e.g.
URL baseUrl = null;
try {
    baseUrl = new URL(completeUrl);
    return new URL(baseUrl.getProtocol(), baseUrl.getHost(), baseUrl.getPort(), "").toString();
} catch (MalformedURLException e) {
    throw new RuntimeException("Invalid URL: " + completeUrl);
StringgetHostName(String url)
Gets a host from given URL
URI uri = new URI(url);
return uri.getHost();
StringgetHostName(String url)
get Host Name
URI uri = new URI(url);
String hostname = uri.getHost();
if (hostname != null) {
    hostname = hostname.startsWith("www.") ? hostname.substring(4) : hostname;
    hostname = uri.getScheme() + "://" + hostname;
    return hostname;
return hostname;
...
StringgetHostName(String url)
Returns the Host Name as a String, parsed from the given URL.
String hostName = url.split("://")[1].split(":")[0];
if (hostName.equals("localhost") || hostName.equals("127.0.0.1")) {
    try {
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        throw new AssertionError(e);
return hostName;
StringgetHostName(String url)
get Host Name
if (url == null || url.length() == 0)
    return "";
url = url.toLowerCase();
if (!url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("ftp://"))
    throw new MalformedURLException("Unknown schema!");
int doubleslash = url.indexOf("//");
doubleslash += 2;
int end = url.length();
...
StringgetHostname(String urlStr)
returns the hostname of the given URL
URL url;
try {
    url = new URL(urlStr);
    String hostname = url.getHost();
    return hostname;
} catch (MalformedURLException e) {
    return null;
String[]getHostSegments(URL url)
Partitions of the hostname of the url by "."
String host = url.getHost();
if (IP_PATTERN.matcher(host).matches())
    return new String[] { host };
return host.split("\\.");