discover static method

Stream<NetworkAddress> discover(
  1. String subnet,
  2. int port, {
  3. Duration timeout = const Duration(milliseconds: 400),
})

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

Pings IP:PORT one by one

Implementation

static Stream<NetworkAddress> discover(
  String subnet,
  int port, {
  Duration timeout = const Duration(milliseconds: 400),
}) async* {
  if (port < 1 || port > 65535) {
    throw 'Incorrect port';
  }
  // TODO : validate subnet

  for (int i = 1; i < 256; ++i) {
    final host = '$subnet.$i';

    try {
      final Socket s = await Socket.connect(host, port, timeout: timeout);
      s.destroy();
      yield NetworkAddress(host, true);
    } catch (e) {
      if (!(e is SocketException)) {
        rethrow;
      }

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