/* This program may cause malfunctioning of the computer you are
connecting to. Please obtain the other system owner's permission before
running this test program. There is a penalty for illegal use of this
kind of program. */

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Test {

    private final static int minport = 1;
    private final static int maxport = 65536;

                   static boolean ports[] = new boolean[maxport]; // neither private nor public, the "default"
                   static String  address = null;

                   static int inprogress=0;

    public static void main (String A[]) {
        BufferedReader CIN=new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.print("Please enter the host name: ");
            address=CIN.readLine();
            System.out.println("SCANNING "+address);

            System.out.print("STARTING: ");
            for (int port=minport; port<ports.length; port++) {
                System.out.print(" "+port);
                new TestPort(port);
                Thread.currentThread().sleep(1); // not necessary
            }
            System.out.println("\n\nALL STARTED");

            while(inprogress>0) {
                System.out.println("\rWAITING FOR "+inprogress+" tests      ");
                Thread.currentThread().sleep(100);
            }

        } catch (Exception e) {
            System.out.println("ERROR: "+e);
        }
        System.out.println("SCAN COMPLETED\n\n\nOPEN TCP/IP PORTS on "+address+":");
        
        for (int i=minport; i<ports.length; i++)
            if (ports[i]) System.out.print(" "+i);
    }

}

class TestPort extends Thread {
    
    private int port=0;
    
    TestPort(int porttotest) {
        port=porttotest;
        Test.inprogress++;
        start(); // starts Thread.start() that spawns run()
    }
    
    public void run() {
        try {

            Socket SO = new Socket(Test.address, port);
            BufferedReader SR=new BufferedReader(new InputStreamReader(SO.getInputStream()));
            PrintWriter SW=new PrintWriter (SO.getOutputStream());
            SW.println("PING!");
            SW.flush();
            SO.close();
            Test.ports[port]=true;
        } catch (Exception e) {
            Test.ports[port]=false;
        }

        Test.inprogress--;
    }
}