/* * 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.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import dns.DNS; import dns.DNSQuery; import dns.DNSUtil; public class NSLookup { private static boolean debug = true; public static void main (String[] args) { if (args.length != 1) throw new IllegalArgumentException ("Syntax: "+ NSLookup.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 { SocketChannel rwChan = SocketChannel.open(); Socket socket = rwChan.socket(); InetAddress destAddr = InetAddress.getByName(nameServer); InetSocketAddress rcvAddress = new InetSocketAddress(destAddr, DNS.DEFAULT_PORT); socket.connect(rcvAddress); socket.setSoTimeout (10000); sendQuery (query, rwChan); getResponse (query, rwChan); rwChan.close (); DNSUtil.printRRs (query); } catch (IOException ex) { ex.printStackTrace(); } } public static void sendQuery (DNSQuery query, SocketChannel chan) throws IOException { byte[] data = query.extractQuery (); ByteBuffer dataBuf = ByteBuffer.allocate(data.length+2); dataBuf.putShort((short)data.length); dataBuf.put(data); dataBuf.flip(); chan.write(dataBuf); } public static void getResponse (DNSQuery query, SocketChannel chan) throws IOException { ByteBuffer dataBuf = ByteBuffer.allocate(2048); chan.read(dataBuf); dataBuf.flip(); int datasize = dataBuf.limit() - 2 ; int responseSize = dataBuf.getShort(); if(debug) { System.out.println("ResponseSize & datasize : " + responseSize + " " + datasize); } byte[] buffer = new byte[datasize]; dataBuf.get(buffer); query.decodeResponse (buffer, buffer.length); } }