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 CheckingIfPortIsFreeisPortFree: true*/