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


advertisement
 

Tip: How to Check Whether a Port is Free

Learn how to check whether or not a given port is free by trying to construct a ServerSocket with the port that needs to be checked.


advertisement

WEBINAR:

On-Demand

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


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

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date