简体   繁体   中英

InetAddress.getAddress() always returns a null, but somehow still works

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM