The SimpleScannerApplet Source Code Now that you know
what the scanner does, let's see how it works. Listing 1 shows the
source code of the SimpleScannerApplet. It extends the
Swing JApplet class and defines two inner classes:
Scanner and ScannerException. The
Scanner class handles the clicking of the Scan button and
performs the actual scanning. The ScannerException class
is used to throw scanner-related exceptions.

It then implements the actionPerformed() method of
java.awt.event.ActionListener to handle the clicking of
the Scan button. It uses the validParameters() method to
determine whether the user supplied a valid host name/IP address and
port number and to convert the users inputs into an
InetAddress object and int port value.

A try-catch statement is used to catch any exceptions
that result from the scanning. An attempt is made to create a TCP
socket to the specified address and port. If the attempt is
successful, then the port is identified as being open and then the
socket is closed. If the attempt is unsuccessful, then an exception is
thrown by the Socket constructor. The catch
block handles this exception by checking to see if the exception is a
SecurityException or some other type of exception.

If a SecurityException is thrown, then the message
associated with the exception is displayed in the Results
field. Otherwise, the port is identified as being closed for the
specified host/IP address.

The Scanner class defines two other methods that support the
scanning process. The validParameters() method checks to
see if the user has entered a valid host/IP address and port number
and then converts those values from String objects to an
InetAddress object and int port value.