Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Get local IP address on Android

How do I get the local IP address of my (Android) device in Flutter? This should be

  • the local IP address I get assigned via DHCP by my router when connected to WIFI
  • the local IP address in the VPN network assigned by my VPN server (not the global IP address by the VPN server itself) if connected to VPN
  • the global IP when connected via cellular
like image 766
Julian Aßmann Avatar asked Oct 27 '25 17:10

Julian Aßmann


1 Answers

I solved it like this for now, but if you have a better solution, that would be deligthful:

import 'dart:io';

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;
        }
      }
    }
  }
like image 107
Julian Aßmann Avatar answered Oct 30 '25 10:10

Julian Aßmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!