簡體   English   中英

InetAddress.getAddress()始終返回null,但不知何故仍然有效

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

我有一個字符串IP地址,我需要轉換為字節數組。 為此,我使用了InetAddress.getByName(ip).getAddress() ,這一切都很有效。

但是,當我查看InetAddress.getAddress()的代碼時,它看起來像這樣:

public byte[] getAddress() {
    return null;
}

這里絕對沒有任何操作 - 但是,我仍然得到一個字節數組,也有核心值。 這是怎么回事?

用於獲取地址的方法, InetAddress.getByName返回一個子類: Inet4AddressInet6Address 這兩個子類實現了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對象的實例化。

因此,因為您獲得了Inet4AddressInet6Address ,並且它們都具有getAddress完整實現,所以您永遠不會真正調用InetAddress.getAddress方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM