Created
August 22, 2012 22:03
How to find an available (free) TCP port in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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"); | |
} |
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
.
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
What about this:
Not exactly equivalent, but way more concise. WDYT?