Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to find an available (free) TCP port in Java
/**
* Returns a free port number on localhost.
*
* Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT just because of this).
* Slightly improved with close() missing in JDT. And throws exception instead of returning -1.
*
* @return a free port number on localhost
* @throws IllegalStateException if unable to find a free port
*/
private static int findFreePort() {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
socket.setReuseAddress(true);
int port = socket.getLocalPort();
try {
socket.close();
} catch (IOException e) {
// Ignore IOException on close()
}
return port;
} catch (IOException e) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on");
}
@fbiville

This comment has been minimized.

Copy link

@fbiville fbiville commented Aug 8, 2014

What about this:

        try (ServerSocket socket = new ServerSocket(0)) {
            socket.setReuseAddress(true);
            return socket.getLocalPort();
        }

Not exactly equivalent, but way more concise. WDYT?

@alxn

This comment has been minimized.

Copy link

@alxn alxn commented Feb 18, 2015

This wont work well if you need need multiple free ports - or have concurrent junit runs.

Need to wrap it as a class that extends org.junit.rules.ExternalResource.

@mnz

This comment has been minimized.

Copy link

@mnz mnz commented Oct 28, 2018

Lines 16 to 20 are not necessary since the code in the finally block will be called anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment