discover2 static method

Stream<NetworkAddress> discover2(
  1. String subnet,
  2. int port, {
  3. Duration timeout = const Duration(seconds: 5),
})

Pings a given subnet (xxx.xxx.xxx) on a given port.

Pings IP:PORT all at once

Implementation

static Stream<NetworkAddress> discover2(
  String subnet,
  int port, {
  Duration timeout = const Duration(seconds: 5),
}) {
  if (port < 1 || port > 65535) {
    throw 'Incorrect port';
  }

  final out = StreamController<NetworkAddress>();
  final futures = <Future<Socket>>[];
  int pending = 255;

  void _checkDone() {
    pending--;
    if (pending <= 0) {
      out.close();
    }
  }

  for (int i = 1; i < 256; ++i) {
    final host = '$subnet.$i';
    final Future<Socket> f = _ping(host, port, timeout);
    futures.add(f);
    f.then((socket) {
      socket.destroy();
      if (!out.isClosed) {
        out.sink.add(NetworkAddress(host, true));
      }
      _checkDone();
    }).catchError((dynamic e) {
      if (e is! SocketException) {
        _checkDone();
        return;
      }

      // Check if connection timed out or we got one of predefined errors
      if (e.osError == null || _errorCodes.contains(e.osError?.errorCode)) {
        if (!out.isClosed) {
          out.sink.add(NetworkAddress(host, false));
        }
      }
      // Error 23,24: Too many open files in system — skip silently
      _checkDone();
    });
  }

  return out.stream;
}