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 27, 2021

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

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();
		serverSocketApp.proceed();
	}

	private void proceed()
	{
		try{
			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
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date