简体   繁体   中英

Flutter/Dart: How to find All Devices Connected to my Local Wifi Network?

I tried using the lan_scanner package ( https://pub.dev/packages/lan_scanner ) but it cannot discover every device on my network. Also its not effective in some other networks such as university or cafeteria, etc.. Any way to perform a successful scan that can find all the devices?

With the use of network_info_plus package and the dart:io package.

import 'dart:io';
import 'package:network_info_plus/network_info_plus.dart';
Future<void> scanNetwork() async {
  await (NetworkInfo().getWifiIP()).then(
    (ip) async {
      final String subnet = ip!.substring(0, ip.lastIndexOf('.'));
      const port = 22;
      for (var i = 0; i < 256; i++) {
        String ip = '$subnet.$i';
        await Socket.connect(ip, port, timeout: Duration(milliseconds: 50))
          .then((socket) async {
            await InternetAddress(socket.address.address)
              .reverse()
              .then((value) {
                print(value.host);
                print(socket.address.address);
              }).catchError((error) {
                print(socket.address.address);
                print('Error: $error');
              });
            socket.destroy();
          }).catchError((error) => null);
      }
    },
  );
  print('Done');
}

I'm "scanning" the local network by trying to connect to a given ip and port. If that works, I found a device, I'm looking for. In that cause I also try to get the hostname by using the "reverse()" method.

I have tested it on several iOS and Android devices and it works fine with no errors, so I think its a proper solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM