3

I have a String IP address that I need to convert to a byte array. For this, I used InetAddress.getByName(ip).getAddress(), and it all works great.

However, when I looked at the code of InetAddress.getAddress(), it looks like this:

public byte[] getAddress() {
    return null;
}

There is absolutely no operation being done here - however, I am still getting a byte array back, with the corerect values too. How is this working?

a3y3
  • 1,025
  • 2
  • 10
  • 34

2 Answers2

2

The method you use to get the address, InetAddress.getByName returns a subclass: either an Inet4Address or an Inet6Address. These 2 subclasses have the getAddress method implemented to return something useful.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

I will add this to further @assylias's answer.

If you look through the source code of InetAddress.getByName you will notice that all it really does, is call down into InetAddress.getAllByName. If you look at the source for that method, you will see the following towards the end:

InetAddress[] ret = new InetAddress[1];

if(addr != null) {
    if (addr.length == Inet4Address.INADDRSZ) {
        ret[0] = new Inet4Address(null, addr);
    } else {
        if (ifname != null) {
            ret[0] = new Inet6Address(null, addr, ifname);
        } else {
            ret[0] = new Inet6Address(null, addr, numericZone);
        }
    }
    return ret;
}

There you can see that InetAddress.getAllByName attempts to determine what version of IP that the address is formatted as. It then instanciates an Inet4/6Address Object based on the format of your input string.

Therefore, because you are getting either Inet4Address or Inet6Address, and they both have full implementations of getAddress, you never really call the InetAddress.getAddress method.

Dylan
  • 1,335
  • 8
  • 21