*
* @throws IOException
*/
public static int findFreePort(int initPort) throws IOException {
int port = -1;
ServerSocket tmpSocket = null;
// first try the default port
try {
tmpSocket = new ServerSocket(initPort);
port = initPort;
System.out.println("Using default port: " + port);
} catch (IOException e) {
System.out.println("Failed to use specified port");
// didn't work, try to find one dynamically
try {
int attempts = 0;
while (port < 1024 && attempts < 2000) {
attempts++;
tmpSocket = new ServerSocket(0);
port = tmpSocket.getLocalPort();
}
} catch (IOException e1) {
throw new IOException(
"Failed to find a port to use for testing: "
+ e1.getMessage());
}
} finally {
if (tmpSocket != null) {
try {
tmpSocket.close();
} catch (IOException e) {
// ignore
}
tmpSocket = null;
}