Jul*_*ann 4 network-programming ip-address dart flutter
如何在 Flutter 中获取我的(Android)设备的本地 IP 地址?这应该是
我现在是这样解决的,但是如果您有更好的解决方案,那就太好了:
static Future<String> getLocalIpAddress() async {
final interfaces = await NetworkInterface.list(type: InternetAddressType.IPv4, includeLinkLocal: true);
try {
// Try VPN connection first
NetworkInterface vpnInterface = interfaces.firstWhere((element) => element.name == "tun0");
return vpnInterface.addresses.first.address;
} on StateError {
// Try wlan connection next
try {
NetworkInterface interface = interfaces.firstWhere((element) => element.name == "wlan0");
return interface.addresses.first.address;
} catch (ex) {
// Try any other connection next
try {
NetworkInterface interface = interfaces.firstWhere((element) => !(element.name == "tun0" || element.name == "wlan0"));
return interface.addresses.first.address;
} catch (ex) {
return null;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4990 次 |
| 最近记录: |