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';
  }
  // TODO : validate subnet

  final out = StreamController<NetworkAddress>();
  final futures = <Future<Socket>>[];
  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();
      out.sink.add(NetworkAddress(host, true));
    }).catchError((dynamic e) {
      if (!(e is SocketException)) {
        throw e;
      }

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

  Future.wait<Socket>(futures)
      .then<void>((sockets) => out.close())
      .catchError((dynamic e) => out.close());

  return out.stream;
}