getFreeListenPort static method

Future<int?> getFreeListenPort({
  1. Iterable<int>? ports,
  2. Iterable<int>? skipPort,
  3. int? startPort,
  4. int? endPort,
  5. bool shufflePorts = false,
  6. Duration? testTimeout,
})

Returns a ServerSocket port free to listen.

  • ports is a List of ports to test.
  • startPort and endPort defines a range of ports to check.
  • If shufflePorts is true 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;
}