What does InetAddress.isSiteLocalAddress() actually mean?

TiGz picture TiGz · Apr 11, 2011 · Viewed 13.1k times · Source

Here is some code to determine the local host name that is supposed to work on a multi-homed box:

 /**
 * Work out the first local host name by iterating the network interfaces
 * 
 * @return
 * @throws SocketException
 */
private String findFirstLocalHostName() throws SocketException {

    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress add = addresses.nextElement();
            if (!add.isLoopbackAddress() && add.isSiteLocalAddress()) {
                return add.getHostName();
            }
        }
    }
    throw new RuntimeException("Failed to determine local hostname");
}

Does the call to isSiteLocalAddress introduce a bug? I can't find any useful information about this method, but I have a feeling that it relates to IP v 6 only and is deprecated.

Answer

Joachim Sauer picture Joachim Sauer · Apr 11, 2011

The method is definitely not deprecated and it's definitely not just used in IPv6.

In IPv4 there are 3 network address ranges that are defined for site-local addresses: 10/8, 172.16/12 and 192.168/16.

Reading Inet4Address.isSiteLocalAddress() shows that addresses from exactly those 3 networks will return true on those methods.

IPv6 has a similar concept, here these addresses are called unqieu local addresses.

Effectively this tells you if the address you have is definitely not a public one (note that even if this method returns false, the address might still not be public).