Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions java/src/org/openqa/selenium/net/PortProber.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,42 @@ public static int findFreePort() {
}

/**
* Returns a random port within the systems ephemeral port range <p/>
* See https://en.wikipedia.org/wiki/Ephemeral_ports for more information. <p/>
* If the system provides a too short range (mostly on old windows systems)
* the port range suggested from Internet Assigned Numbers Authority will be used.
* Returns a port that is within a probable free range. <p/> Based on the ports in
* http://en.wikipedia.org/wiki/Ephemeral_ports, this method stays away from all well-known
* ephemeral port ranges, since they can arbitrarily race with the operating system in
* allocations. Due to the port-greedy nature of selenium this happens fairly frequently.
* Staying within the known safe range increases the probability tests will run green quite
* significantly.
*
* @return a random port number
*/
private static int createAcceptablePort() {
synchronized (random) {
int FIRST_PORT = Math.max(START_OF_USER_PORTS, ephemeralRangeDetector.getLowestEphemeralPort());
int LAST_PORT = Math.min(HIGHEST_PORT, ephemeralRangeDetector.getHighestEphemeralPort());
final int FIRST_PORT;
final int LAST_PORT;

if (LAST_PORT - FIRST_PORT < 5000) {
int ephemeralStart = Math.max(START_OF_USER_PORTS, ephemeralRangeDetector.getLowestEphemeralPort());
int ephemeralEnd = Math.min(HIGHEST_PORT, ephemeralRangeDetector.getHighestEphemeralPort());

/*
* If the system provides a too short range of ephemeral ports (mostly on old windows systems)
* use the range suggested from Internet Assigned Numbers Authority as ephemeral port range.
*/
if (ephemeralEnd - ephemeralStart < 5000) {
EphemeralPortRangeDetector ianaRange = new FixedIANAPortRange();
FIRST_PORT = ianaRange.getLowestEphemeralPort();
LAST_PORT = ianaRange.getHighestEphemeralPort();
ephemeralStart = ianaRange.getLowestEphemeralPort();
ephemeralEnd = ianaRange.getHighestEphemeralPort();
}

int freeAbove = HIGHEST_PORT - ephemeralEnd;
int freeBelow = Math.max(0, ephemeralStart - START_OF_USER_PORTS);

if (freeAbove > freeBelow) {
FIRST_PORT = ephemeralEnd;
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralStart;
}

if (FIRST_PORT == LAST_PORT) {
Expand Down