向 Android 中的域发送 DNS 查询

Sending DNS query to a domain in Android

我正在尝试发送一条 DNS 查询消息,假设 www.google.com 获取 DNS 的 A 记录。我阅读了 this 文章以找出 DNS 查询的结构。

我将缓冲区消息创建为:

 private static final byte[] RequestPacket = {

            // Transaction ID: 0x0000
            0x00, 0x00,

            // Flags: 0x0000 (Standard query)
            0x00, 0x00,

            // Questions: 1
            0x00, 0x01,

            // Answer RRs: 0
            0x00, 0x00,

            // Authority RRs: 0
            0x00, 0x00,

            // Additional RRs: 0
            0x00, 0x00,

            // Queries
            // Name: www.google.com
            0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x03, 0x63,
            0x6F, 0x6D, 0x00,

            // Type: A Record
            0x00, 0x01

    };

这就是我创建发送、接收数据包和套接字的方式:

DatagramPacket sendPacket = new DatagramPacket(RequestPacket , RequestPacket .length, InetAddress.getByName("www.google.com"), 9876);
DatagramPacket recievePacket = new DatagramPacket(mBuffer, mBuffer.length);
DatagramSocket socket = new DatagramSocket();

发送数据包后调用socket.receive(recievePacket);时,我无法收到任何回复(SocketTimeoutException)

我想我弄乱了发送数据包的端口,但在搜索 google 很多时间后,我找到了查询 DNS 的端口。

有人能告诉我我到底做错了什么吗?

谢谢

InetAddress.getByName() 为您执行 DNS 查询和 returns 指定主机的 IP 地址(主机可能有多个 IP 地址,如果您需要它们,请使用 getAllByName()相反)。

在您的示例中,getByName("www.google.com") returns Google 的 HTTP 服务器的 IP 地址,不是 DNS 服务器。您不能将 DNS 查询发送到 HTTP 服务器。这就是您没有收到回复的原因。

如果您真的想发送自己的 DNS 查询,则需要将它们定向到真实的 DNS 服务器,例如您的 Wifi/Cellular 网络提供商提供的服务器(参见 How do you get the current DNS servers for Android?), or a third-party DNS server (like Google's Public DNS)。