2016-11-06 66 views
0

我寫一個程序來檢查一個給定的IP地址是否是任何本地地址或不作爲:InetAddress對象在調用isAnyLocalAddress()時如何返回true?

import java.net.*; 
class GetByName 
{ 
     public static void main(String[] args) throws Exception 
     { 
       byte[] b = {0, 0, 0, 0}; 
       String s = "abc"; 
       InetAddress in = InetAddress.getByAddress(b); 
       boolean b1 = in.isAnyLocalAddress(); 
       System.out.println(in); 
       System.out.println(b1); 
     } 
} 

,輸出是:

/0.0.0.0 
true 

是的,看着挺正常的。但是當我在InetAddress.java中看到isAnyLocalAddress()的實現時,我感到震驚。

public boolean isAnyLocalAddress() { 
    return false; 
} 

意味着無論如何該方法必須返回false。那麼這個方法在我的程序中如何返回true?

+3

它在子類中被覆蓋。 – tkausl

+0

@tkausl但對象是InetAddress類型,而不是Inet4Address .. –

+1

Are you sure? https://ideone.com/sinGV7 – tkausl

回答

0

如果你看一下這個方法是如何在AOSP source code實施:

private static InetAddress getByAddress(String hostName, byte[] ipAddress, int scopeId) throws UnknownHostException { 
    if (ipAddress == null) { 
     throw new UnknownHostException("ipAddress == null"); 
    } 
    if (ipAddress.length == 4) { 
     return new Inet4Address(ipAddress.clone(), hostName); 
    } else if (ipAddress.length == 16) { 
     // First check to see if the address is an IPv6-mapped 
     // IPv4 address. If it is, then we can make it a IPv4 
     // address, otherwise, we'll create an IPv6 address. 
     if (isIPv4MappedAddress(ipAddress)) { 
      return new Inet4Address(ipv4MappedToIPv4(ipAddress), hostName); 
     } else { 
      return new Inet6Address(ipAddress.clone(), hostName, scopeId); 
     } 
    } else { 
     throw badAddressLength(ipAddress); 
    } 
} 

你會看到,返回的Inet4AddressInet6Address之一。進一步看,Inet4Address實現爲:

@Override public boolean isAnyLocalAddress() { 
    return ipaddress[0] == 0 && ipaddress[1] == 0 && ipaddress[2] == 0 && ipaddress[3] == 0; // 0.0.0.0 
} 

Inet6Address是:

@Override public boolean isAnyLocalAddress() { 
    return Arrays.equals(ipaddress, Inet6Address.ANY.ipaddress); 
} 

無論是空操作,如默認實現。

相關問題