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

标签 flutter dart network-programming ip-address

如何在 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 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63514434/

    相关文章:

    http - flutter 错误 : type 'AddressInfo' is not a subtype of type 'String' in type cast

    android - 由于Firebase分析导致Gradle失败

    dart - 什么是boot.js(Dart)

    Flutter 背景 Firebase 通信

    firebase - 向Cloud Firestore添加阵列(Flutter/Dart)

    firebase - 使用where子句更新Firebase

    c++ - 如何通过 irDA 套接字建立连接?

    Python - 在公共(public)互联网协议(protocol)上创建套接字服务器

    python - 从 IP 地址获取主机名

    api - Flutter:如何在不进行API调用的情况下重新渲染 View ?