如何在 Flutter 中获取公共 IP?

Nan*_*a Z 2 dart flutter

就我而言,我需要公共 IP 地址。但是,在研究了几乎所有与本地 IP 相关的纪录片后,例如:Get_IP,我想要像 202.xxx 而不是 192.168.xxx 这样的东西。有人可以给一些建议吗?

Abi*_*n47 10

据我所知,无法从该设备内部获取该设备的公共 IP。这是因为在绝大多数情况下,设备不知道自己的公共 IP。公网 IP 是由 ISP 分配给设备的,您的设备通常通过任意数量的调制解调器、路由器、交换机等与 ISP 分离。

您需要查询一些外部资源或 API(例如ipify.org),然后它会告诉您您的公共 IP 是什么。您可以通过一个简单的 HTTP 请求来做到这一点。

import 'package:http/http.dart';

Future<String> getPublicIP() async {
  try {
    const url = 'https://api.ipify.org';
    var response = await http.get(url);
    if (response.statusCode == 200) {
      // The response body is the IP in plain text, so just
      // return it as-is.
      return response.body;
    } else {
      // The request failed with a non-200 code
      // The ipify.org API has a lot of guaranteed uptime 
      // promises, so this shouldn't ever actually happen.
      print(response.statusCode);
      print(response.body);
      return null;
    }
  } catch (e) {
    // Request failed due to an error, most likely because 
    // the phone isn't connected to the internet.
    print(e);
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:现在有一个Dart 包,用于从 IPify 服务获取公共 IP 信息。您可以使用此包代替上述手动解决方案:

import 'package:dart_ipify/dart_ipify.dart';

void main() async {
  final ipv4 = await Ipify.ipv4();
  print(ipv4); // 98.207.254.136

  final ipv6 = await Ipify.ipv64();
  print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e

  final ipv4json = await Ipify.ipv64(format: Format.JSON);
  print(ipv4json); //{"ip":"98.207.254.136"} or {"ip":"2a00:1450:400f:80d::200e"}

  // The response type can be text, json or jsonp
}
Run Code Online (Sandbox Code Playgroud)