Flutter/Dart:扫描本地网络以获取已连接设备的IP和主机名

4
我正在使用Flutter开发移动应用程序,并希望扫描本地网络上连接的设备。我找到了ping_discover_network包,它运行良好,但只能获取IP地址,我还想显示设备的主机名。
我尝试使用dart:io包中InternetAddress类的reverse()方法,但这只会返回IP地址。例如:
InternetAddress(ip).reverse().then((value) => print(value));

有没有其他的包或工具可以用来扫描应用程序所在的本地网络,并获取IP地址和主机名?

2个回答

7

好的,我解决了这个问题并想分享我的解决方案。

我使用了network_info_plus包和dart:io包。

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');
}

我正在通过尝试连接给定的IP地址和端口来“扫描”本地网络。如果成功连接,我就找到了我要寻找的设备。我还尝试使用“reverse()”方法获取主机名。

我已在多个iOS和Android设备上测试过,没有出现错误,因此我认为这是一个适当的解决方案。


-1

我认为这在桌面上不起作用,因为它没有被实现。 仅适用于iOS和Android。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接