/*
  file:         PortView.java
  purpose:      a simple port probing utility
  created:      pasha long time ago
  modified:     pasha oct 6 2000
  modification: 1. allow one port number in args
                2. more accurate exceptions handling
  pending:
*/


import java.io.PrintStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.net.Socket;


public class PortView
{
    public PortView () {}

    public static void main (String[] args)
    {
	if ((args.length != 2) && (args.length != 3))
	    {
		System.out.println (
	  "Usage  : java PortView <machine_name> <from> [to]\n"
	+ "Example: java PortView wincrap 80 88"
	                           );
		System.exit (1);
	    }

        String machine = args[0];
        int from = Integer.parseInt (args[1]);
	int to = (args.length == 2 ? from : Integer.parseInt (args[2]));
		
        for (int i=from; i<=to; i++)
	    {
		System.out.print ("testing port " + i + " on " + machine + ": ");
		new PortConnection (machine, i);
	    }
        System.out.println ("finished");
    }
} // end of class PortView



class PortConnection
{
    protected Socket sock;
    protected DataInputStream from;
    protected PrintStream to;

    public PortConnection (String host, int port)
    {
	try
	    {
		sock = new Socket (host, port);
		from = new DataInputStream (sock.getInputStream());
		to = new PrintStream (sock.getOutputStream());
		System.out.println ("connected");
	    }
	catch (UnknownHostException e)
	    {
		System.out.println (e.toString());
		System.exit (2);
	    }
	catch (IOException e)
	    {
		System.out.println (e.toString());
	    }
	finally
	    {
	        if (sock != null)
		    {
			try
			    {   
				sock.close(); 
			    }
			catch (IOException ex) {}
		    }
	    }
    }
} // end of class PortConnection


// end of PortView.java

