Skip to content

Instantly share code, notes, and snippets.

@reyabreu
Created December 9, 2019 15:51
Show Gist options
  • Save reyabreu/3cd9c6dab5ab45b00c34c183db295b4d to your computer and use it in GitHub Desktop.
Save reyabreu/3cd9c6dab5ab45b00c34c183db295b4d to your computer and use it in GitHub Desktop.
A utility class that provides a method for finding a random freely available TCP/IP port. Mostly used in integration tests.
public class TestUtils {
// an AutoCloseable bean is needed to guarantee the found port is freed before we can use it
private static class SocketHolder implements Closeable {
private final ServerSocket socket;
public SocketHolder(ServerSocket socket) {
this.socket = socket;
}
public ServerSocket getSocket() {
return socket;
}
@Override
public void close() throws IOException {
socket.close();
}
}
public static int findFreePort() {
// cf. https://gist.github.com/3429822
try (SocketHolder holder = new SocketHolder(new ServerSocket(0))) {
holder.getSocket().setReuseAddress(true);
return holder.getSocket().getLocalPort();
}
catch (IOException e) {
throw new IllegalStateException("Could not open an available free port", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment