Flutter:在Android上获取本地IP地址

问题描述

如何在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;
        }
      }
    }
  }