[英]InetAddress.getAddress() always returns a null, but somehow still works
我有一个字符串IP地址,我需要转换为字节数组。 为此,我使用了InetAddress.getByName(ip).getAddress()
,这一切都很有效。
但是,当我查看InetAddress.getAddress()
的代码时,它看起来像这样:
public byte[] getAddress() {
return null;
}
这里绝对没有任何操作 - 但是,我仍然得到一个字节数组,也有核心值。 这是怎么回事?
用于获取地址的方法, InetAddress.getByName
返回一个子类: Inet4Address
或Inet6Address
。 这两个子类实现了getAddress
方法以返回有用的东西。
我将这个添加到@ assylias的答案中。
如果你仔细查看InetAddress.getByName
的源代码,你会注意到它真正做的就是调用InetAddress.getAllByName
。 如果您查看该方法的来源,您将看到以下内容:
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;
}
在那里,您可以看到InetAddress.getAllByName
尝试确定将地址格式化为的IP版本。 然后根据输入字符串的格式实现Inet4/6Address
对象的实例化。
因此,因为您获得了Inet4Address
或Inet6Address
,并且它们都具有getAddress
完整实现,所以您永远不会真正调用InetAddress.getAddress
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.