How to find a free port — Java

Jaspreet Kaur
Sep 5, 2023

--

import java.io.IOException;
import java.net.ServerSocket;

public static int findAFreePort() {
try {
ServerSocket server = new ServerSocket(0);
int port = server.getLocalPort();
server.close();
return port;
} catch (IOException ex) {
throw new RuntimeException("Failed to find a free port.", ex);
}
}

I am using this post a documentation for myself. Nothing much say, code block is self explanatory.

--

--