gpt4 book ai didi

java - Windows 上的反向 dns 查找会阻止无法解析的 IP 地址几秒钟

转载 作者:可可西里 更新时间:2023-11-01 11:51:31 25 4
gpt4 key购买 nike

我正在使用 Java 的 InetAddress.getHostName() 执行一些反向 DNS 查找,但它所花费的时间似乎有问题。这是一个代码片段:

public static void main(String[] args) throws IOException {

byte[][] addresses = new byte[][] { { 10, (byte) 0, (byte) 0, (byte) 138 }
, new byte[] { (byte) 216, (byte) 239, (byte) 49, (byte) 245 }
,{ 8, (byte) 8, (byte) 8, (byte) 8 } };

for (byte[] addr : addresses) {
InetAddress inet = InetAddress.getByAddress(addr);
long before = System.currentTimeMillis();
String hostName = inet.getHostName();
System.out.printf("%20s %40s %5d\n", inet.getHostAddress(), hostName, (System.currentTimeMillis() - before));
}
}

这是我机器上的输出:

    10.0.0.138                               10.0.0.138  4503
216.239.49.245 216.239.49.245 4591
8.8.8.8 google-public-dns-a.google.com 8

无论我运行这段代码多少次,解析 10.0.0.138 和 216.239.49.245 都需要 4.5 秒。这似乎发生在所有无法解析的 IP 地址上。

这不是网络问题,因为根据 wireshark 捕获,运行此代码时 甚至不会发送 DNS 查询除非先清除 DNS 缓存 (然后结果甚至更慢 - 每个分辨率大约 4.7 秒)。

那么 Java 是否真的需要 4.5 秒才能针对操作系统的本地 DNS 缓存超时?这是没有意义的。命令行实用程序 nslookup 可以更快地返回这些 IP 地址的(无法解析的)结果,而且它甚至不使用缓存!

有人可以解释这种行为并提出加速这些决议的方法吗?在不求助于外部库的情况下,我唯一能想到的就是使用多线程,因此至少 4.5 秒的超时将并行执行。

作为引用,我在 Windows 7 x64 上使用 JDK 7u71

编辑1: This问题似乎相关,但那里的答案说性能取决于网络,这不是我观察到的。

编辑2:

这似乎是 Windows 的问题。同一局域网中的一台机器,使用完全相同的 DNS,运行带有 JDK 1.7u67 的 OpenSuse 13.1 返回以下结果:

没有 DNS 缓存:

10.0.0.138                                   10.0.0.138  116             
216.239.49.245 216.239.49.245 5098
8.8.8.8 google-public-dns-a.google.com 301

使用 DNS 缓存:

10.0.0.138                                   10.0.0.138  5
216.239.49.245 216.239.49.245 9
8.8.8.8 google-public-dns-a.google.com 40

编辑3:

最终我不得不通过使用 dnsjava 进行我自己的反向 DNS 查找来解决这个问题。 .

最佳答案

这看起来像是 Windows 中 DNS 客户端实现的问题。我刚刚在 C#.NET 中尝试了相同的逻辑:

 static void Main(string[] args)
{
byte[][] addresses = new byte[][] { new byte[] { 10, (byte) 0, (byte) 0, (byte) 138 },
new byte[] { (byte) 216, (byte) 239, (byte) 49, (byte) 245 },
new byte []{ 8, (byte) 8, (byte) 8, (byte) 8 } };
foreach (byte[] addr in addresses)
{
IPAddress inet = new IPAddress(addr);
DateTime before = DateTime.Now;
String hostName = null;
try
{
hostName = System.Net.Dns.GetHostByAddress(inet).HostName;
}
catch { }
finally
{
DateTime after = DateTime.Now;
Console.WriteLine("{0} {1} {2}", inet.ToString(), hostName!=null?hostName:"N/A", after.Subtract(before));
}
}
Console.ReadLine();
}

这些是结果:

   10.0.0.138 N/A 00:00:04.5604560
216.239.49.245 N/A 00:00:04.7984798
8.8.8.8 google-public-dns-a.google.com 00:00:00.0060006

有趣的是,在刷新 DNS 缓存后,Windows 将所有 DNS 请求发送到网络。 DNS 服务器在 0.25 秒后回复,但如果答案是“No Such Name”,则 DNS 客户端在整个超时期间仍会阻塞。

关于java - Windows 上的反向 dns 查找会阻止无法解析的 IP 地址几秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com