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

Ate*_*rus 4 networking dart flutter

我正在使用 Flutter 开发移动应用程序,并且想要扫描本地网络以查找连接的设备。我找到了ping_discover_network包,它工作正常,但只能获取 IP 地址,但我还想显示设备的主机名。

我尝试了 dart:io 包中 InternetAddress 类的 reverse() 方法,但这只能取回 IP 地址。例子:

InternetAddress(ip).reverse().then((value) => print(value));
Run Code Online (Sandbox Code Playgroud)

是否有其他软件包或其他我可以使用的东西来扫描应用程序的本地网络并获取 IP 地址和主机名?

Ate*_*rus 8

好的,我已经成功了,想分享我的解决方案。

我使用了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');
}
Run Code Online (Sandbox Code Playgroud)

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

我已经在几个 iOS 和 Android 设备上测试过它,它运行良好,没有错误,所以我认为它是一个正确的解决方案。