Skip to content

Instantly share code, notes, and snippets.

@vorburger
Created August 22, 2012 22:03
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vorburger/3429822 to your computer and use it in GitHub Desktop.
Save vorburger/3429822 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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
Copy link

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