Sending DNS query to a domain in Android

僤鯓⒐⒋嵵緔 提交于 2019-12-08 12:26:41

问题


I am trying to send a DNS query message to let's say www.google.com to get A record of DNS. I read this article to find out the structure of DNS query.

I created the buffer message as:

 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

    };

That's how I am creating send, receive packets and my socket as well:

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

I am not able to receive any response back(SocketTimeoutException) when I call socket.receive(recievePacket); after sending the packet

I think I am messing up with the port of my send packet, but after searching google for a lot of time that's the port I found to query for DNS.

Can somebody tell me what exactly am I doing wrong?

Thanks


回答1:


InetAddress.getByName() performs a DNS query for you and returns an IP address of the specified host (the host may have multiple IP addresses, if you need them all then use getAllByName() instead).

In your example, getByName("www.google.com") returns an IP address for Google's HTTP server, NOT a DNS server. You cannot send DNS queries to an HTTP server. This is why you are not getting a response back.

If you really want to send your own DNS queries, you need to direct them to a real DNS server, like the one provided by your Wifi/Cellular network provider (see How do you get the current DNS servers for Android?), or a third-party DNS server (like Google's Public DNS).



来源:https://stackoverflow.com/questions/38562137/sending-dns-query-to-a-domain-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!