scanPorts method

Future<List<PortCheckResult>> scanPorts({
  1. required String host,
  2. List<int> ports = const <int>[80, 443],
  3. Duration? timeout,
  4. int concurrency = 12,
})

并发扫描多个端口 / Scans multiple ports with bounded concurrency.

结果顺序与 ports 一致 / Results preserve the order of ports.

Implementation

Future<List<PortCheckResult>> scanPorts({
  required String host,
  List<int> ports = const <int>[80, 443],
  Duration? timeout,
  int concurrency = 12,
}) async {
  if (ports.isEmpty) return const <PortCheckResult>[];

  final results = List<PortCheckResult?>.filled(ports.length, null);
  var cursor = 0;

  Future<void> worker() async {
    while (true) {
      final index = cursor;
      cursor += 1;
      if (index >= ports.length) return;
      results[index] = await checkPort(
        host: host,
        port: ports[index],
        timeout: timeout,
      );
    }
  }

  final workerCount = math.min(math.max(1, concurrency), ports.length);
  await Future.wait(
    List<Future<void>>.generate(workerCount, (_) => worker()),
  );
  return results.whereType<PortCheckResult>().toList(growable: false);
}