2

I write a program to check whether a given IP address is Any Local Address or not as:

import java.net.*;
class GetByName
{
        public static void main(String[] args) throws Exception
        {
                byte[] b = {0, 0, 0, 0};
                String s = "abc";
                InetAddress in = InetAddress.getByAddress(b);
                boolean b1 = in.isAnyLocalAddress();
                System.out.println(in);
                System.out.println(b1);
        }
}

And the output is:

/0.0.0.0
true

Yes, looking quite normal. But I shocked when I see the implementation of isAnyLocalAddress() in InetAddress.java.

public boolean isAnyLocalAddress() {
   return false;
}

Means anyhow this method has to return false. Then how this method returns true in my program?

my name is GYAN
  • 1,139
  • 9
  • 22

1 Answers1

4

If you look at how this method is implemented in the AOSP source code:

private static InetAddress getByAddress(String hostName, byte[] ipAddress, int scopeId) throws UnknownHostException {
    if (ipAddress == null) {
        throw new UnknownHostException("ipAddress == null");
    }
    if (ipAddress.length == 4) {
        return new Inet4Address(ipAddress.clone(), hostName);
    } else if (ipAddress.length == 16) {
        // First check to see if the address is an IPv6-mapped
        // IPv4 address. If it is, then we can make it a IPv4
        // address, otherwise, we'll create an IPv6 address.
        if (isIPv4MappedAddress(ipAddress)) {
            return new Inet4Address(ipv4MappedToIPv4(ipAddress), hostName);
        } else {
            return new Inet6Address(ipAddress.clone(), hostName, scopeId);
        }
    } else {
        throw badAddressLength(ipAddress);
    }
}

You will see that one of Inet4Address or Inet6Address is returned. Looking further, Inet4Address is implemented as:

@Override public boolean isAnyLocalAddress() {
    return ipaddress[0] == 0 && ipaddress[1] == 0 && ipaddress[2] == 0 && ipaddress[3] == 0; // 0.0.0.0
}

and Inet6Address is:

@Override public boolean isAnyLocalAddress() {
    return Arrays.equals(ipaddress, Inet6Address.ANY.ipaddress);
}

Neither are no-ops like the default implementation.

pathfinderelite
  • 2,767
  • 20
  • 26