Flutter:在 Android 上获取本地 IP 地址
Flutter: Get local IP address on Android
如何在 Flutter 中获取我的 (Android) 设备的本地 IP 地址?
这应该是
- 当连接到 WIFI 时,我的路由器通过 DHCP 分配的本地 IP 地址
- 如果连接到 VPN,则由我的 VPN 服务器分配的 VPN 网络中的本地 IP 地址(不是 VPN 服务器本身的全局 IP 地址)
- 通过蜂窝网络连接时的全球 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;
}
}
}
}
如何在 Flutter 中获取我的 (Android) 设备的本地 IP 地址? 这应该是
- 当连接到 WIFI 时,我的路由器通过 DHCP 分配的本地 IP 地址
- 如果连接到 VPN,则由我的 VPN 服务器分配的 VPN 网络中的本地 IP 地址(不是 VPN 服务器本身的全局 IP 地址)
- 通过蜂窝网络连接时的全球 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;
}
}
}
}