/* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import dns.*; public class UDPNSLookupBase { public static void main (String[] args) { if (args.length != 1) throw new IllegalArgumentException ("Syntax: "+ UDPNSLookupBase.class.getName()+" [@]"); int atIdx = args[0].indexOf ("@"); String nameServer = (atIdx > -1) ? args[0].substring (atIdx + 1) : "ns"; String hostName = (atIdx > -1) ? args[0].substring (0, atIdx) : args[0]; System.out.println ("Nameserver: " + nameServer); System.out.println ("Request: " + hostName); DNSQuery query = new DNSQuery (hostName, DNS.TYPE_ANY, DNS.CLASS_IN); try { boolean received = false; int count = 0; DatagramChannel sndChan = null; /* TODO * create the datagramChannel */ DatagramSocket socket = sndChan.socket(); socket.setSoTimeout (5000); try { while (!received) { try { sendQuery (query, sndChan, InetAddress.getByName (nameServer)); getResponse (query, sndChan); received = true; } catch (InterruptedIOException ex) { if (count ++ < 3) { System.out.println ("resend.."); } else { throw new IOException ("No response received from nameserver"); } } } } finally { sndChan.close(); } DNSUtil.printRRs (query); } catch (IOException ex) { ex.printStackTrace(); System.out.println (ex); } } public static void sendQuery (DNSQuery query, DatagramChannel chan, InetAddress nameServer) throws IOException { byte[] data = query.extractQuery (); InetSocketAddress rcvAddress; rcvAddress = new InetSocketAddress(nameServer, DNS.DEFAULT_PORT); /* TODO * send the data obtained from the query to the datagramChannel * at the server referred by the InetAddress to the default DNS port DNS.DEFAULT_PORT (53) */ } public static void getResponse (DNSQuery query, DatagramChannel chan) throws IOException { /* TODO * receive at max 512 bytes from the server as a response * put data in buffer and data size in size */ int size = 0; byte[] buffer = null; query.decodeResponse (buffer, size); } }