Dart如何获取本地IP地址?


#1

如何获取本地非127.0.0.1的IP地址?


#2

如果是内网地址,可以使用NetworkInterface;如果想获取公网ip,可行方法之一是通过http请求ip查询网站,然后解析请求结果得到

import 'dart:io';
import 'dart:convert';

main(List<String> args) async {
  // 内网ip
  for (var interface in await NetworkInterface.list()) {
    for (var addr in interface.addresses) {
      print('${addr.address}');
    }
  }

  // 外网ip
  var ipRegexp = RegExp(
      r'((?:(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d))\.){3}(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d)))');
  var url = 'http://www.ip.cn/';
  var client = HttpClient();
  var request = await client.getUrl(Uri.parse(url));
  var reponse = await request.close();
  reponse.transform(utf8.decoder).forEach((line) {
    ipRegexp.allMatches(line).forEach((match) {
      print(match.group(0));
    });
  });
}

#3

Flutter中应该怎么获取?我这么写报错:
SocketException: Failed listing interfaces (OS Error: Listing interfaces is not supported on this platform)


#4

:sweat_smile: Flutter的NetworkInterface好像只支持ios,没有办法,只能用插件了:https://pub.flutter-io.cn/packages/get_ip