Member-only story

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response