Flutter : Android에서 로컬 IP 주소 가져 오기
Aug 21 2020
Flutter에서 내 (Android) 기기의 로컬 IP 주소를 얻으려면 어떻게해야합니까? 이것은
- WiFi에 연결되었을 때 라우터에서 DHCP를 통해 할당받은 로컬 IP 주소
- VPN에 연결된 경우 VPN 서버가 할당 한 VPN 네트워크의 로컬 IP 주소 (VPN 서버 자체의 글로벌 IP 주소가 아님)
- 셀룰러를 통해 연결된 경우 글로벌 IP
답변
1 JulianAßmann Sep 02 2020 at 05:53
지금은 이렇게 해결했지만 더 나은 해결책이 있다면 성실 할 것입니다.
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;
}
}
}
}