Java Host Name Get getShortHostname()

Here you can find the source of getShortHostname()

Description

get Short Hostname

License

Apache License

Return

A short hostname (using of this computer's host name.

Declaration

public static String getShortHostname() 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.net.InetAddress;

import java.net.UnknownHostException;

public class Main {
    /**//from   w  w  w .j a va 2s  .  c o m
     * @return A short hostname (using {@link #extractShortHostname} of this computer's host name.
     */
    public static String getShortHostname() {
        return extractShortHostname(getHostname());
    }

    /**
     * @param hostname Hostname to shorten
     * @return Short hostname - everything till the first dot, excluding domain. E.g. for {@code hostname.domain.tld} you will get {@code hostname}
     */
    public static String extractShortHostname(final String hostname) {
        final int firstDot = hostname.indexOf('.');
        if (firstDot > 0) {
            final String result = hostname.substring(0, firstDot);
            // We happened to get an IP address most likely, let's retain it.
            if (isNumeric(result)) {
                return hostname;
            }
            return result;
        }
        return hostname;
    }

    /**
     * @return Hostname of this computer, e.g. {@code hostname.domain.tld}
     */
    public static String getHostname() {
        String hostName;
        final InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
            hostName = localHost.getHostName();
        } catch (UnknownHostException ignore) {
            hostName = "localhost";
        }
        return hostName;
    }

    public static boolean isNumeric(String str) {
        try {
            Integer.parseInt(str);
        } catch (NumberFormatException ignore) {
            return false;
        }
        return true;
    }
}

Related

  1. getProxy(String host, String proxyType)
  2. getServerHost()
  3. getShortHostName()
  4. getShortHostName()
  5. getShortHostname()
  6. getTimerServerHost()