flutter 自帶的dart:io 庫(kù)就可以支持獲取設(shè)備的 ipv4 和ipv6地址.
flutter 獲取的ipv6地址字符串跟iOS 原生獲取的ipv6地址,稍微有區(qū)別:
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 最后會(huì) 拼上 %en0,為了保證數(shù)據(jù)的一致性,所以需要用空替換
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 {
// 獲取所有網(wǎng)絡(luò)接口信息
List<NetworkInterface> interfaces = await NetworkInterface.list(
includeLoopback: true, // 是否包含回環(huán)接口
includeLinkLocal: true, // 是否包含鏈路本地接口(例如IPv6的自動(dòng)配置地址)。
type: InternetAddressType.any,
);
// 遍歷所有網(wǎng)絡(luò)接口
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);
}
}
}