Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

How to send a DNS query in java using DataGrampacket

HI,
I wrote the following program  :
import sun.net.spi.nameservice.dns.DNSNameService;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDP {
    public static void main(String[] args) {
        DatagramSocket skt;
        try {
            skt = new DatagramSocket();
            String msg = "www.google.com";
            byte[] b = msg.getBytes();
            InetAddress host = InetAddress.getByName("172.16.41.48");
            int serverSocket = 53;
            DatagramPacket request = new DatagramPacket(b, b.length, host, serverSocket);
            skt.send(request);
            byte[] buffer = new byte[1000];
            DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
            skt.receive(reply);
            skt.close();
            System.out.println(new String(request.getData()));
            System.out.println(new String(reply.getData()));
        } catch (Exception ex) {
            System.out.printf("Exception : ", ex);
        }
    }
}

Open in new window


I dont receive any response in this. The ip address you see is my DNS server. I see an error in wireshark  :
Malformed packet: DNS. This is most likely because i am only sending a string containing the hostname in the UDP packet. It probably needs a proper DNS query to be send in it.
How do i construct this proper DNS query ? Is there any class in java that can help in this ?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Steve Bink
Steve Bink
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj

ASKER

Will respond back soon.