How to find free ports after SocketUtils has been deprecated in spring boot 3?

176 Views Asked by At

org.springframwork.util.SocketUtils has been deprecated in spring boot 3. Please provide a code snippet on how to find free ports within a specified range.

I am interested in alternate solutions for SocketUtils.findAvailableTcpPorts(requestedNumberOfPorts, minimumPortValue, maximumPortValue) which would return any requested no. of ports from a specified range and SocketUtils.findAvailableTcpPort(minimumPortValue, maximumPortValue)

1

There are 1 best solutions below

0
On BEST ANSWER

Another alternative is to use Java's ServerSocket class to find available TCP ports. Here's a code snippet how you can do it, HTH.

import java.net.ServerSocket;

private static boolean isPortAvailable(int port) {
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        return true;
    } catch (IOException e) {
        // Port is not available
        return false;
    }