我编写了一个程序来检查给定的 IP 地址是否为任何本地地址,如下所示:
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呢?
最佳答案
如果你看看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);
}
}
您将看到返回了 Inet4Address
或 Inet6Address
之一。进一步看,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);
}
也不像默认实现那样无操作。
关于java - InetAddress 对象在调用 isAnyLocalAddress() 时如何返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40450687/