dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Aug 29, 2019

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


How to Check Whether a Port is Free

We can check if a given port is free by trying to construct a ServerSocket with the port that needs to be checked:

import java.io.*;
import java.net.*;

public class CheckingIfPortIsFree
{
   public static void main(String args[])
   {
      CheckingIfPortIsFree checkingIfPortIsFree = new CheckingIfPortIsFree();
      checkingIfPortIsFree.proceed();
   }
   
   private void proceed()
   {
      int portToBeChecked = 4567;
      boolean isPortFree;
      
      try {
         ServerSocket serverSocket = new ServerSocket(portToBeChecked);
         isPortFree = true;
      }
      catch (IOException ioe)
      {
        isPortFree = false;
      }

      System.out.println("isPortFree: " + isPortFree);
   }
}

/*

Expected output:

[root@mypc]# java CheckingIfPortIsFree
isPortFree: true

*/
M S Sridhar
 
Thanks for your registration, follow us on our social networks to keep up-to-date