Class PortFactory
- Author:
- jamesdbloom
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic intstatic int[]findFreePorts(int count) Find multiple free ports.
-
Field Details
-
PORT_RANGE_START_PROPERTY
Opt-in test-port band. When BOTH properties are set to a valid range,findFreePort()andfindFreePorts(int)draw their candidates by explicitly binding ports inside[start, end]rather than bybind(0).Why this exists.
bind(0)asks the OS for an ephemeral port, drawn from the same range every otherbind(0)on the machine uses (macOSnet.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 (aBindException), 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 tobind(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
- 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 handleBindExceptionas 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
countdistinct port numbers that were recently free - Throws:
IllegalArgumentException- if count is not between 1 and 1000
-