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

问题:

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?


回答1:

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.


回答2:

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.

  • 发表于 2019-03-17 18:25
  • 阅读 ( 180 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除