Java Local Host Get getLocalHostName()

Here you can find the source of getLocalHostName()

Description

Retrieves the local host's hostname.

License

Apache License

Declaration

public static String getLocalHostName() throws SocketException, UnknownHostException 

Method Source Code


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

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main {
    private static final String REGEX_IP_ADDRESS = "\\d+(\\.\\d+){3}";

    /**//w  w  w .  j  a  v  a 2 s . co m
     * Retrieves the local host's hostname. If found, the fully qualified domain name (FQDN) will be returned,
     * otherwise it will fallback to the unqualified domain name. E.g prefer guerrero.moocar.me over guerrero.
     */
    public static String getLocalHostName() throws SocketException, UnknownHostException {
        try {
            final String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();
            if (isFQDN(canonicalHostName)) {
                return canonicalHostName;
            } else {
                return InetAddress.getLocalHost().getHostName();
            }
        } catch (UnknownHostException e) {
            NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
            if (networkInterface == null)
                throw e;
            InetAddress ipAddress = networkInterface.getInetAddresses().nextElement();
            if (ipAddress == null)
                throw e;
            return ipAddress.getHostAddress();
        }
    }

    /**
     * Returns true is the hostname is a Fully Qualified Domain Name (FQDN)
     */
    private static boolean isFQDN(String hostname) {
        return hostname.contains(".") && !hostname.matches(REGEX_IP_ADDRESS);
    }
}

Related

  1. getLocalHostName()
  2. getLocalHostName()
  3. getLocalHostName()
  4. getLocalHostName()
  5. getLocalhostName()
  6. getLocalHostName()
  7. getLocalHostName()
  8. getLocalHostname()
  9. getLocalHostName(boolean includeDomain)