在运行时为Java中的InetAddress禁用IPv6解析

时间:2019-01-21 11:55:30

标签: java dns

我正在写一个小的http测试库,在某个时候它应该解析给定域的IP。我使用InetAddress.getAllByName,但这会导致某些罕见的域出现异常(只能解析IPv4地址),我看不出如何避免这种情况。换句话说,对于这样的域,我什至无法获得IPv4地址,因为我不能仅对它们单独进行呼叫。

让我们看一个例子。具有以下代码:

public static void main(String ... args) throws Exception {
    for (InetAddress addr : Inet4Address.getAllByName(args[0])) {
        System.out.println(addr);
    }
}

我们可以执行以下操作:

$ java InetAddressTest amazon.com

但是对于某些主机,我们可能会收到令人讨厌的异常:

$ java InetAddressTest quantcount.com

Exception in thread "main" java.net.UnknownHostException: quantcount.com: Name or service not known
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1324)
at java.net.InetAddress.getAllByName0(InetAddress.java:1277)
at java.net.InetAddress.getAllByName(InetAddress.java:1193)
at java.net.InetAddress.getAllByName(InetAddress.java:1127)
at InetAddressTest.main(InetAddressTest.java:6)

请注意,Inet4Address.getAllByName仍然会引起Inet6AddressImpl的错误,因为该方法实际上与InetAddress相同。

这受某些属性控制,因此此调用有效:

java -Djava.net.preferIPv4Stack=true InetAddressTest quantcount.com

但是该属性(as specified)无法在运行时更新。

一种解决方法是使用某些库进行dns查找,而无需依赖Inet.getAllByName调用。但是,这里不是我缺少的标准API中明显的标志或东西吗-可能仅允许查找IPv4地址?

(我正在为此项目使用java8)

0 个答案:

没有答案
相关问题