Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Determining the Active Ports in Java

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Here we are going to look at the approach of identifying the available and active ports used as a server.

Approach:

1. Create an object of Socket class.

2. Assign a value to i up to which you want to look for the available ports.

3. Pass this integer and hostname to the object of socket class.

Example:

Java




// Java program to check the active or available
// ports.
 
import java.net.*;
import java.io.*;
 
public class Main {
    public static void main(String[] args)
    {
        // Creating object of socket class
        Socket portCheck;
 
        // Defining the hostName to check for port
        // availability
        String host = "localhost";
 
        if (args.length > 0) {
            host = args[0];
        }
        for (int i = 0; i < 1024; i++) {
            try {
                System.out.println("Looking for " + i);
                portCheck = new Socket(host, i);
                System.out.println(
                    "There is a server running on port "
                    + i);
            }
            catch (UnknownHostException e) {
                System.out.println("Exception occurred" + e);
                break;
            }
            catch (IOException e) {
            }
        }
    }
}


Output:

Check ports availability


My Personal Notes arrow_drop_up
Last Updated : 08 Jun, 2022
Like Article
Save Article
Similar Reads
Related Tutorials