dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Apr 26, 2021

Java: How to Find If a Port Is Free

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 = "127.0.0.1";
	static int portToConnect = 6789;
	
	public static void main(String args[])
	{
		FindPortIsFree findPortIsFree = new FindPortIsFree();
		findPortIsFree.proceed(hostToConnect,portToConnect);
	}

	private void proceed(String hostName, int portToConnect)
	{
		Socket socket = null;
		try
		{
			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.
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date