Skip to content

Commit

Permalink
Improve ephemeral port range selection. Fixes issue 3868
Browse files Browse the repository at this point in the history
  • Loading branch information
krosenvold committed Jan 22, 2013
1 parent 1f0cad2 commit abe546e
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions java/client/src/org/openqa/selenium/net/PortProber.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,27 +83,33 @@ public Integer call()
* @return a random port number
*/
private static int createAcceptablePort() {
synchronized (random) {

final int FIRST_PORT;
final int LAST_PORT;
if (ephemeralRangeDetector.getHighestEphemeralPort() < 32768){
FIRST_PORT = ephemeralRangeDetector.getHighestEphemeralPort() + 1;
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort() - 1;
synchronized (random) {


final int FIRST_PORT;
final int LAST_PORT;

int free_above = 65535 - ephemeralRangeDetector.getHighestEphemeralPort();
int free_below = Math.max(0, ephemeralRangeDetector.getLowestEphemeralPort() - 1024);

if (free_above > free_below) {
FIRST_PORT = ephemeralRangeDetector.getHighestEphemeralPort();
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort();
}

if (FIRST_PORT == LAST_PORT) {
return FIRST_PORT;
}
if (FIRST_PORT > LAST_PORT) {
throw new UnsupportedOperationException("Could not find ephemeral port to use");
}
final int randomInt = random.nextInt();
final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
return portWithoutOffset + FIRST_PORT;
}
if (FIRST_PORT == LAST_PORT) {
return FIRST_PORT;
}
if (FIRST_PORT > LAST_PORT) {
throw new UnsupportedOperationException("Could not find ephemeral port to use");
}
final int randomInt = random.nextInt();
final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
return portWithoutOffset + FIRST_PORT;
}
}

private static int checkPortIsFree(int port) {
Expand Down

0 comments on commit abe546e

Please sign in to comment.