Using a Java Socket Class to Find Open Port: Second Method

Tuesday Apr 27th 2021 by MS Sridhar
Article Image

We discuss a second method for discovering if a port is available using the Java Sockets class in this Java programming and developer tip.

Java Socket Class to Find Open Port: Second Method

In a previous Java tip, we showcased how to create a short program, using some simple code and the Socket class, to discover whether or not a port was in use or check its availability. In this follow-up, we will learn a second method to check port availability using the Java programming language.

Here is some sample code, written in Java, that you can use to check a port’s state:

import java.net.*;

public class ServerSocketApp
	int portToConnect = 6789;
	public static void main(String args[])
		ServerSocketApp serverSocketApp = new ServerSocketApp();

	private void proceed()
			ServerSocket serverSocket = new ServerSocket(portToConnect);  
			System.out.println("Server listening on port " + portToConnect);

			Socket socket = serverSocket.accept();
		}catch(Exception exception)
			System.out.println("Exception: " + exception);



If you entered the Java code correctly, you should see the following output:

$java ServerSocketApp
Server listening on port 6789
Mobile Site | Full Site