Java Local Host Get getCanonicalLocalHostName()

Here you can find the source of getCanonicalLocalHostName()

Description

get Canonical Local Host Name

License

Open Source License

Declaration

public static String getCanonicalLocalHostName() throws UnknownHostException, SocketException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static String getCanonicalLocalHostName() throws UnknownHostException, SocketException {
        try {/*from w w w .j  a v  a2 s .  c o  m*/
            InetAddress localhost = InetAddress.getLocalHost();
            return localhost.getCanonicalHostName();
        } catch (UnknownHostException e) {
            return getLocalAddressAsString();
        }
    }

    private static String getLocalAddressAsString() throws UnknownHostException, SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces != null && interfaces.hasMoreElements()) {
            Enumeration<InetAddress> addresses = interfaces.nextElement().getInetAddresses();
            while (addresses != null && addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (acceptableAddress(address)) {
                    return address.getHostAddress();
                }
            }
        }
        throw new UnknownHostException();
    }

    private static boolean acceptableAddress(InetAddress address) {
        return address != null && !address.isLoopbackAddress() && !address.isAnyLocalAddress()
                && !address.isLinkLocalAddress();
    }
}

Related

  1. createLocalHostID(int size)
  2. getAllLocalHostNames()
  3. getCanonicalLocalHostName()
  4. getLocalHost()
  5. getLocalHost()
  6. getLocalhost()
  7. getLocalHost()