Home » Tip Bank » Java
  • Comment on this Article
Language: Java
Expertise: Intermediate
Aug 29, 2019
  • facebook
  • twitter
  • in
  • Email



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();
   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
Submit a Tip
Browse "Java" Tips
Browse All Tips