// $Id: DHCPListener.java,v 1.9 2004/11/03 16:17:05 dphull Exp $

import java.io.IOException;
import java.io.PrintStream;
import java.net.SocketException;


public final class DHCPListener
{
    private DHCPPacketDecoder decoder;
    private DHCPSocket dhcpSocket;

    public DHCPListener(String fingerprintsFile) throws SocketException
    {
        dhcpSocket = new DHCPSocket();
        decoder = new DHCPPacketDecoder(fingerprintsFile);
    }

    public static void main(String[] args) throws SocketException
    {
				String fingerprintsFile;
				if (args.length != 1) 
				{
					System.out.println();
					System.out.println("Usage: java DHCPListener \"<fingerPrintsFile>\"");
					System.out.println();
				} else 
				{
					fingerprintsFile = args[0];
				  DHCPListener dhcpListener = new DHCPListener(fingerprintsFile);
					PrintStream out = new PrintStream(System.out);
	        dhcpListener.run(out);
				}
    }

    public void run(PrintStream out)
    {
        byte[] rawPacket = null;

        out.print(DHCPClientInformation.getHeader());
    
        while (true)
        {
            try
            {
                rawPacket = dhcpSocket.getNextPacket();
            }
            catch (IOException e)
            {
                e.printStackTrace(out);
            }

            DHCPClientInformation dci = decoder.decode(rawPacket);
            if(dci.getMessageType().equals("DISCOVER") ||
               dci.getMessageType().equals("REQUEST"))
            {
              out.println(dci.toString());
              out.flush();
            }
        }
    }
}
