diff --git a/java/src/org/openqa/selenium/net/PortProber.java b/java/src/org/openqa/selenium/net/PortProber.java index 0ff011e00d02e..1706432ee1c5f 100644 --- a/java/src/org/openqa/selenium/net/PortProber.java +++ b/java/src/org/openqa/selenium/net/PortProber.java @@ -64,22 +64,42 @@ public static int findFreePort() { } /** - * Returns a random port within the systems ephemeral port range

- * See https://en.wikipedia.org/wiki/Ephemeral_ports for more information.

- * 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.

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) {