[英]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. 我有一个字符串IP地址,我需要转换为字节数组。 For this, I used
InetAddress.getByName(ip).getAddress()
, and it all works great. 为此,我使用了
InetAddress.getByName(ip).getAddress()
,这一切都很有效。
However, when I looked at the code of InetAddress.getAddress()
, it looks like this: 但是,当我查看
InetAddress.getAddress()
的代码时,它看起来像这样:
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
. 用于获取地址的方法,
InetAddress.getByName
返回一个子类: Inet4Address
或Inet6Address
。 These 2 subclasses have the getAddress
method implemented to return something useful. 这两个子类实现了
getAddress
方法以返回有用的东西。
I will add this to further @assylias's answer. 我将这个添加到@ assylias的答案中。
If you look through the source code of InetAddress.getByName
you will notice that all it really does, is call down into InetAddress.getAllByName
. 如果你仔细查看
InetAddress.getByName
的源代码,你会注意到它真正做的就是调用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. 在那里,您可以看到
InetAddress.getAllByName
尝试确定将地址格式化为的IP版本。 It then instanciates an Inet4/6Address
Object based on the format of your input string. 然后根据输入字符串的格式实现
Inet4/6Address
对象的实例化。
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. 因此,因为您获得了
Inet4Address
或Inet6Address
,并且它们都具有getAddress
完整实现,所以您永远不会真正调用InetAddress.getAddress
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.