美文网首页
flutter 获取设备ipv4 和ipv6地址

flutter 获取设备ipv4 和ipv6地址

作者: YannChee | 来源:发表于2024-04-18 11:16 被阅读0次

    flutter 自带的dart:io 库就可以支持获取设备的 ipv4 和ipv6地址.
    flutter 获取的ipv6地址字符串跟iOS 原生获取的ipv6地址,稍微有区别:

    iOS 
    ipv4:  192.168.3.81
    ipv6: fe80::2:7cc7:ca39:fe4d
    
    flutter:
    IPv4 address: 192.168.3.81
    IPv6 address: fe80::2:7cc7:ca39:fe4d%en0 
    

    可以看到 flutter获取的 ipv6 最后会 拼上 %en0,为了保证数据的一致性,所以需要用空替换
    tempIpv6 = tempIpv6.replaceAll("%en0", "");

    import 'dart:io';
    import 'package:flutter/foundation.dart';
    
    class IpV4AndIpV6Tool {
      static Future<void> getIpv4AndIpV6Addresses(
          Function(String ipv4Address, String ipv6Address)
              didClickConfirmBtnAction) async {
        String tempIpv4 = "";
        String tempIpv6 = "";
        try {
          // 获取所有网络接口信息
          List<NetworkInterface> interfaces = await NetworkInterface.list(
            includeLoopback: true, // 是否包含回环接口
            includeLinkLocal: true, // 是否包含链路本地接口(例如IPv6的自动配置地址)。
            type: InternetAddressType.any,
          );
    
          // 遍历所有网络接口
          for (var interface in interfaces) {
            // check if interface is en0 which is the wifi conection on the iphone
            if (interface.name != 'en0') {
              continue;
            }
            print('Interface name: ${interface.name}');
            // 遍历接口的地址
            for (var address in interface.addresses) {
              if (address.address.isNotEmpty) {
                if (address.type == InternetAddressType.IPv4) {
                  tempIpv4 = address.address;
                  if (kDebugMode) {
                    print('IPv4 address: $tempIpv4');
                  }
                } else if (address.type == InternetAddressType.IPv6) {
                  tempIpv6 = address.address;
                  if (tempIpv6.contains("%en0")) {
                    tempIpv6 = tempIpv6.replaceAll("%en0", "");
                  }
    
                  if (kDebugMode) {
                    print('IPv6 address: $tempIpv6');
                  }
                }
              }
            }
          }
        } catch (e) {
          print('Failed to get IP addresses: $e');
        } finally {
          didClickConfirmBtnAction(tempIpv4, tempIpv6);
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:flutter 获取设备ipv4 和ipv6地址

          本文链接:https://www.haomeiwen.com/subject/pfaexjtx.html