How to check open port in java

This example shows you how to check the open port in localhost using java.

Below is the example code of checking open port in java for a host name.

package com.java.connect.net;
 
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
 
//Check open port in java
 
public class NetworkOpenPortExample {
    public static void main(String[] args) throws Exception {
        // Get the localhost address
        InetAddress inetAddress = InetAddress.getByName("localhost");
        // Get the Hostname
        String localhost = inetAddress.getHostName();
        // Check from 0 to 9999 port
        for (int port = 0; port <= 9999; port++) {
            try {
                // Try to create the Socket on the port.
                // If you fail to create the Socket.
                // Socket is not open
                Socket socket = new Socket(localhost, port);
                String message = port + " is open in " + localhost;
                System.out.println(message);
                socket.close();
            } catch (IOException e) {
                // If fail to create Socket,
                // The port is not open
                String message = port + " is not open in " + localhost;
                System.out.println(message);
            }
        }
    }
}

The above example print the open and used port: