How do I create port scanner program?

In this example you’ll see how to create a simple port scanner program to check the open ports for the specified host name.

package org.kodejava.example.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class PortScanner {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        InetAddress inetAddress = InetAddress.getByName(host);

        String hostName = inetAddress.getHostName();
        for (int port = 0; port <= 65535; port++) {
            try {
                Socket socket = new Socket(hostName, port);
                String text = hostName + " is listening on port " + port;
                System.out.println(text);
                socket.close();
            } catch (IOException e) {
                // empty catch block
            }
        }
    }
}

The result of the code snippet above are:

localhost is listening on port 53
localhost is listening on port 80
localhost is listening on port 443
localhost is listening on port 631
localhost is listening on port 1099
localhost is listening on port 3306
localhost is listening on port 4380
localhost is listening on port 6942
localhost is listening on port 8005
localhost is listening on port 8009
localhost is listening on port 8021
localhost is listening on port 8080
...