Java Local Host Get getLocalHost()

Here you can find the source of getLocalHost()

Description

Smarter way to get localhost than InetAddress.getLocalHost.

License

Apache License

Declaration

private static InetAddress getLocalHost() throws UnknownHostException, SocketException 

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;
import java.util.Enumeration;

public class Main {
    /**/*  w  ww  . ja  v  a  2  s .c  o  m*/
     * Smarter way to get localhost than InetAddress.getLocalHost.  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
     */
    private static InetAddress getLocalHost() throws UnknownHostException, SocketException {
        // Windows Vista returns the IPv6 InetAddress using this method, which is not
        // particularly useful as it has no name or useful address, just "0:0:0:0:0:0:0:1".
        // That is why windows should be treated differently to linux/unix and use the
        // default way of getting the localhost.
        String osName = System.getProperty("os.name");
        if (osName != null && osName.toLowerCase().contains("windows")) {
            return InetAddress.getLocalHost();
        }

        InetAddress loopback = null;
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface i = e.nextElement();
            if (i.isUp() && !i.isPointToPoint()) {
                Enumeration<InetAddress> ie = i.getInetAddresses();
                while (ie.hasMoreElements()) {
                    InetAddress lch = ie.nextElement();
                    if (lch.isLoopbackAddress()) {
                        loopback = lch;
                    } else if (!lch.isLinkLocalAddress()) {
                        return lch;
                    }
                }
            }
        }
        return loopback;
    }
}

Related

  1. getLocalHost()
  2. getLocalHost()
  3. getLocalHost()
  4. getLocalHost()
  5. getLocalHost()
  6. getLocalHost()
  7. getLocalHost()
  8. getLocalHostAddress()
  9. getLocalHostAddress()