Java 6: get localhost address reliablely








package test;

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

public class IPAddrUtil {

    public static void main(String[] args) throws Throwable {
        System.out.println(getLocalhostAddress());
    }

    public static InetAddress getLocalhostAddress() throws Throwable {
        // NOTE: prefer the LAN address over loopback address
        InetAddress addr = getLocalAreaNetworkAddress();
        if (addr == null) {
            addr = getLoopbackAddress();
        }
        return addr;
    }

    public static InetAddress getLocalAreaNetworkAddress() throws Throwable {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = ifaces.nextElement();
            if (!iface.isLoopback()) {
                for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address.isSiteLocalAddress()) {
                        return address;
                    }
                }
            }
        }
        return null;
    }

    public static InetAddress getLoopbackAddress() throws Throwable {
        InetAddress v4Addr = null;
        InetAddress v6Addr = null;
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = ifaces.nextElement();
            if (iface.isLoopback()) {
                for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address.isLoopbackAddress()) {
                        String hostAddress = address.getHostAddress();
                        if (hostAddress.indexOf('.') >= 0) {
                            v4Addr = address;
                        }
                        if (hostAddress.indexOf(':') >= 0) {
                            v6Addr = address;
                        }
                    }
                }
            }
        }
        // NOTE: prefer v4 address over v6 address
        if (v4Addr != null) {
            return v4Addr;
        } else if (v6Addr != null) {
            return v6Addr;
        } else {
            return null;
        }
    }
}

see also




No comments:

Post a Comment