Class PortFactory

java.lang.Object
org.mockserver.socket.PortFactory

public class PortFactory extends Object
Author:
jamesdbloom
  • Field Details

    • PORT_RANGE_START_PROPERTY

      public static final String PORT_RANGE_START_PROPERTY
      Opt-in test-port band. When BOTH properties are set to a valid range, findFreePort() and findFreePorts(int) draw their candidates by explicitly binding ports inside [start, end] rather than by bind(0).

      Why this exists. bind(0) asks the OS for an ephemeral port, drawn from the same range every other bind(0) on the machine uses (macOS net.inet.ip.portrange.hifirst..hilast, typically 49152-65535) - including unrelated applications, IDE helpers, and other JVMs. Two problems follow on a busy developer machine: a foreign process listening in that range can occupy a number we are about to choose (a BindException), and, worse, a test that connects to a just-selected-but-not-yet-bound port can reach a foreign listener instead of the server under test - producing responses from software that is not MockServer at all. Binding inside a band the OS does not itself hand out to bind(0) avoids that whole class of cross-application collision.

      Opt-in on purpose. Both properties are unset by default, so CI and any machine that does not set them keep the original bind(0) behaviour byte-for-byte. A machine that suffers ephemeral-range collisions sets, for example, -Dmockserver.testPortRangeStart=20000 -Dmockserver.testPortRangeEnd=40000. In a surefire/failsafe fork this must reach the fork, e.g. via -Dmockserver.testArgLine="-Dmockserver.testPortRangeStart=20000 -Dmockserver.testPortRangeEnd=40000".

      Setting exactly one of the two, or an unparseable / out-of-order / too-narrow range, is a misconfiguration and is raised loudly rather than silently ignored.

      See Also:
    • PORT_RANGE_END_PROPERTY

      public static final String PORT_RANGE_END_PROPERTY
      See Also:
  • Constructor Details

    • PortFactory

      public PortFactory()
  • Method Details

    • findFreePort

      public static int findFreePort()
    • findFreePorts

      public static int[] findFreePorts(int count)
      Find multiple free ports. Ports are selected from a larger pool of recently-available ports to reduce the chance of collisions. Callers should handle BindException as the returned ports may be claimed by another process before the caller binds them.
      Parameters:
      count - the number of free ports to find (must be between 1 and 1000 inclusive)
      Returns:
      an array of count distinct port numbers that were recently free
      Throws:
      IllegalArgumentException - if count is not between 1 and 1000