getFreeListenPort static method
Returns a ServerSocket port free to listen.
ports
is a List of ports to test.startPort
andendPort
defines a range of ports to check.- If
shufflePorts
istrue
the ports order will be random.
Implementation
static Future<int?> getFreeListenPort(
{Iterable<int>? ports,
Iterable<int>? skipPort,
int? startPort,
int? endPort,
bool shufflePorts = false,
Duration? testTimeout}) async {
var checkPortsSet = <int>{};
if (ports != null) {
checkPortsSet.addAll(ports);
}
if (startPort != null && endPort != null) {
if (startPort <= endPort) {
for (var p = startPort; p <= endPort; ++p) {
checkPortsSet.add(p);
}
} else {
for (var p = endPort; p <= startPort; ++p) {
checkPortsSet.add(p);
}
}
}
var checkPorts = checkPortsSet.toList();
if (skipPort != null) {
checkPorts.removeWhere((p) => skipPort.contains(p));
}
if (shufflePorts) {
checkPorts.shuffle();
}
for (var port in checkPorts) {
if (await isFreeListenPort(port, testTimeout: testTimeout)) {
return port;
}
}
return null;
}