[英]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.