Java: How to Find If a Port Is Free

Monday Apr 26th 2021 by MS Sridhar
Article Image

Java has a Socket class that can connect to a port on a specified host. Using this, we can check to see if a port is available or not.

Java Method to Check Port Availability

Java has a Socket class that can establish a connection to a port on a specified host. We can figure out if the port is occupied or not based on the success of the socket instance being established. This logic can be utilized to make informed decisions that are dependent upon a port's availability.

Here is an example of how to check if a port is free using Java code:


import java.net.*;

public class FindPortIsFree
	static String hostToConnect = "";
	static int portToConnect = 6789;
	public static void main(String args[])
		FindPortIsFree findPortIsFree = new FindPortIsFree();

	private void proceed(String hostName, int portToConnect)
		Socket socket = null;
			socket = new Socket(hostName, portToConnect);
			System.out.println("Successfully bound to port " + portToConnect);
			System.out.println("An app is listening on port " + portToConnect + " and hence it is not free.");
		catch (Exception exception)
			System.err.println("Exception: " + exception);
			System.out.println("Possible reason that the no app port is not listening.");


If you entered the Java code correctly, your output should look like this:

$java FindPortIsFree
Successfully bound to port 6789
An app is listening on port 6789 and hence it is not free.
Mobile Site | Full Site