Created
August 2, 2018 21:45
-
-
Save loganlinn/efcae58e806df1fb73790355ddd8905a to your computer and use it in GitHub Desktop.
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
import java.io.IOException; | |
import java.net.ServerSocket; | |
public class ServerTestUtils { | |
/** | |
* 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 | |
*/ | |
public 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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment