public class PortScanner extends JFrame
1: //PortScanner.java
2: //Scans ports 1 to 256 and reports which ones are active.
4: import java.awt.Color;
5: import java.awt.FlowLayout;
6: import java.awt.event.ActionEvent;
7: import java.awt.event.ActionListener;
8: import java.net.InetAddress;
9: import java.net.Socket;
10: import java.net.UnknownHostException;
11: import java.io.IOException;
12: import javax.swing.JButton;
13: import javax.swing.JFrame;
14: import javax.swing.JScrollPane;
15: import javax.swing.JTextArea;
16: import javax.swing.JTextField;
18: public class PortScanner extends JFrame
19: implements ActionListener
20: {
21: private JTextField hostName;
22: private JTextArea report;
23: private JButton button;
24: private JScrollPane scroller;
26: public static void main(String [] args)
27: {
28: PortScanner app = new PortScanner("Port Scanner");
29: app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30: app.setSize(580, 210);
31: app.setVisible(true);
32: }
34: PortScanner(String s)
35: {
36: super(s);
37: getContentPane().setBackground(Color.CYAN);
39: button = new JButton("Enter host name above, then click here to " +
40: "display server ports found on that host ...");
41: hostName = new JTextField("cs.stmarys.ca", 50);
42: report = new JTextArea(8, 50);
43: scroller = new JScrollPane(report);
45: setLayout(new FlowLayout());
46: add(hostName);
47: add(button);
48: add(scroller);
50: button.addActionListener(this);
51: }
52:
53: public void actionPerformed(ActionEvent event)
54: {
55: report.setText("");
56: String host = hostName.getText();
57: try
58: {
59: InetAddress theAddress = InetAddress.getByName(host);
60: for (int i=0; i<256; i++)
61: {
62: try
63: {
64: Socket socket = new Socket(host, i);
65: report.append("Active server on port " + i + "\n");
66: report.setCaretPosition(0);
67: socket.close();
68: }
69: catch (IOException e)
70: {
71: //Commented out to reduce amount of output
72: //report.append("Exception: No server on port " +
73: // i + ": " + e.toString());
74: }
75: }
76: }
77: catch (UnknownHostException e)
78: {
79: report.setText("Unknown host");
80: }
81: }
82: }