Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does InetAddress.isSiteLocalAddress() actually mean?

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.

like image 306
TiGz Avatar asked Apr 11 '11 09:04

TiGz


People also ask

What is InetAddress getLocalHost ()?

Java InetAddress getLocalHost() method The getLocalHost() method of Java InetAddress class returns the instance of InetAddress containing local host name and address. In this, firstly the host name is retrieved from the system, then that name is resolved into InetAddress.

What is InetAddress getByName?

The getByName() method of InetAddress class determines the IP address of a host from the given host's name. If the host name is null, then an InetAddress representing an address of the loopback interface is returned.


2 Answers

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).

like image 89
Joachim Sauer Avatar answered Oct 11 '22 16:10

Joachim Sauer


Looking at the implementation...

For an Inet4Address, it checks to see if it's one of the RFC1918 "unrouteable" addresses: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.

For an Inet6Address, it checks the first two octets to see if it's a real "site local" address.

like image 25
dty Avatar answered Oct 11 '22 15:10

dty