/* * 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.ByteBuffer; import java.nio.channels.DatagramChannel; import dns.*; public class UDPNSLookup { public static void main (String[] args) { if (args.length != 1) throw new IllegalArgumentException ("Syntax: "+ UDPNSLookup.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 = DatagramChannel.open(); DatagramSocket socket = sndChan.socket(); socket.setSoTimeout (1000); try { while (!received) { try { sendQuery (query, sndChan, InetAddress.getByName (nameServer),2053); 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, int port) throws IOException { byte[] data = query.extractQuery (); ByteBuffer dataBuf = ByteBuffer.allocate(512); dataBuf.clear(); dataBuf.put(data); dataBuf.flip(); InetSocketAddress rcvAddress; rcvAddress = new InetSocketAddress(nameServer, port); chan.send(dataBuf, rcvAddress); } public static void getResponse (DNSQuery query, DatagramChannel chan) throws IOException, InterruptedIOException { ByteBuffer dataBuf = ByteBuffer.allocate(512); dataBuf.clear(); chan.receive(dataBuf); dataBuf.flip(); int size = dataBuf.limit(); byte[] buffer = new byte[size]; dataBuf.get(buffer); query.decodeResponse (buffer, size); } }