905086
2026-11-07 6697e53613d5ce562a19795ab41b19803c2bb93d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import 'dart:convert';
import 'dart:io';
 
import 'package:dio/dio.dart';
 
/// 电脑网络信息
class NetworkInfo {
  final String connType; // 连接方式(WLAN/以太网)
  final String localIp; // 内网IP
  final String gateway; // 网关
  final String dns; // DNS服务器
  final String publicIp; // 公网IP
  final String location; // 地区
  final String isp; // 运营商
 
  const NetworkInfo({
    this.connType = '未知',
    this.localIp = '未知',
    this.gateway = '未知',
    this.dns = '未知',
    this.publicIp = '获取失败',
    this.location = '未知',
    this.isp = '未知',
  });
}
 
NetworkInfo? _cache;
DateTime? _cacheAt;
 
/// 获取真实的网络信息(结果缓存10分钟,避免频繁请求)
Future<NetworkInfo> getNetworkInfo() async {
  if (_cache != null &&
      _cacheAt != null &&
      DateTime.now().difference(_cacheAt!) < const Duration(minutes: 10)) {
    return _cache!;
  }
  // 公网信息(多源降级)与本地网卡信息并行获取
  final results = await Future.wait([
    _fetchPublicInfo(),
    _fetchLocalInfo(),
  ]);
  final pub = results[0] as Map<String, String>?;
  final local = results[1] as Map<String, String?>;
 
  final info = NetworkInfo(
    connType: local['if'] ?? '未知',
    localIp: local['ip'] ?? '未知',
    gateway: local['gw'] ?? '未知',
    dns: local['dns'] ?? '未知',
    publicIp: pub?['ip'] ?? '获取失败',
    location: pub?['location'] ?? '未知',
    isp: pub?['isp'] ?? '未知',
  );
  _cache = info;
  _cacheAt = DateTime.now();
  return info;
}
 
Dio _dio() => Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 5),
      // 部分公共IP接口返回非200状态码
      validateStatus: (status) => status != null && status < 500,
    ));
 
/// 公网IP/地区/运营商:依次尝试多个源,取第一个成功的
Future<Map<String, String>?> _fetchPublicInfo() async {
  final dio = _dio();
  final sources = <Future<Map<String, String>?> Function(Dio)>[
    _fromIpipNet,
    _fromUserAgentInfo,
    _fromIpApiCom,
  ];
  for (final fetch in sources) {
    try {
      final r = await fetch(dio);
      if (r != null && (r['ip'] ?? '').isNotEmpty) return r;
    } catch (_) {
      // 尝试下一个源
    }
  }
  return null;
}
 
/// 源1:myip.ipip.net,返回文本"当前 IP:x.x.x.x  来自于:中国 广东 深圳  电信"
Future<Map<String, String>?> _fromIpipNet(Dio dio) async {
  final res = await dio.get<String>('https://myip.ipip.net');
  final text = res.data ?? '';
  final m = RegExp(r'当前 IP:(.+?)\s*来自于:(.+)').firstMatch(text);
  if (m == null) return null;
  final parts = m.group(2)!.trim().split(RegExp(r'\s+'));
  final isp = parts.isNotEmpty ? parts.removeLast() : '';
  return {
    'ip': m.group(1)!.trim(),
    'location': parts.join(' '),
    'isp': isp,
  };
}
 
/// 源2:ip.useragentinfo.com,返回JSON {"ip":"x.x.x.x","country":"中国","province":"广东省","city":"广州市","isp":"电信"}
Future<Map<String, String>?> _fromUserAgentInfo(Dio dio) async {
  final res = await dio.get('https://ip.useragentinfo.com/json');
  final d = res.data;
  if (d is! Map) return null;
  final location = [d['country'], d['province'], d['city']]
      .whereType<String>()
      .where((s) => s.isNotEmpty)
      .join(' ');
  final ip = (d['ip'] ?? '').toString();
  if (ip.isEmpty) return null;
  return {'ip': ip, 'location': location, 'isp': (d['isp'] ?? '').toString()};
}
 
/// 源3:ip-api.com,返回JSON {"query":"x.x.x.x","country":"中国","regionName":"广东","city":"深圳","isp":"..."}
Future<Map<String, String>?> _fromIpApiCom(Dio dio) async {
  final res =
      await dio.get('http://ip-api.com/json/?lang=zh-CN&fields=query,isp,org,as');
  final d = res.data;
  if (d is! Map) return null;
  final ip = (d['query'] ?? '').toString();
  if (ip.isEmpty) return null;
  // isp多为英文AS描述,转成常见中文运营商名
  final org = '${d['isp']} ${d['org']} ${d['as']}'.toUpperCase();
  String isp = d['isp'].toString();
  if (org.contains('CHINANET') || org.contains('TELECOM') || org.contains('电信')) {
    isp = '电信';
  } else if (org.contains('UNICOM') || org.contains('联通')) {
    isp = '联通';
  } else if (org.contains('CMNET') || org.contains('MOBILE') || org.contains('移动')) {
    isp = '移动';
  } else if (org.contains('TIETONG') || org.contains('铁通')) {
    isp = '铁通';
  } else if (org.contains('CERNET')) {
    isp = '教育网';
  } else if (org.contains('GWBN')) {
    isp = '长城宽带';
  } else if (isp.isEmpty) {
    isp = '未知';
  }
  return {'ip': ip, 'location': '未知', 'isp': isp};
}
 
/// 本地网卡信息:连接方式/内网IP/网关/DNS(PowerShell查询)
Future<Map<String, String?>> _fetchLocalInfo() async {
  const script = r'''
$nic = Get-NetIPConfiguration | Where-Object {
  $_.NetAdapter.Status -eq 'Up' -and
  $_.NetAdapter.InterfaceDescription -notmatch 'VMware|Virtual|Hyper-V|VirtualBox|WSL|TAP|Loopback|Bluetooth' -and
  @($_.IPv4Address.IPAddress) -match '^(?!169\.254\.|127\.)' -and @($_.IPv4Address.IPAddress).Count -gt 0
}
$c = $nic | Where-Object { $null -ne $_.IPv4DefaultGateway } | Select-Object -First 1
if ($null -eq $c) { $c = $nic | Select-Object -First 1 }
if ($null -eq $c) { '{}' | Write-Output } else {
  $ips = @($c.IPv4Address.IPAddress | Where-Object { $_ -notmatch '^169\.254\.|^127\.' })
  $dns = (Get-DnsClientServerAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -eq $c.InterfaceAlias -and $_.ServerAddresses }).ServerAddresses -join ','
  @{ ip = [string]$ips[0]; gw = [string]$c.IPv4DefaultGateway.NextHop; if = [string]$c.InterfaceAlias; dns = [string]$dns } | ConvertTo-Json -Compress
}
''';
  try {
    final res = await Process.run('powershell', ['-NoProfile', '-Command', script]);
    if (res.exitCode != 0) return const {};
    final out = (res.stdout as String).trim();
    if (out.isEmpty) return const {};
    final d = jsonDecode(out);
    if (d is! Map) return const {};
    String? val(Object? v) {
      final s = v?.toString() ?? '';
      return s.isEmpty ? null : s;
    }
 
    // 连接方式映射:WLAN→无线网络,以太网→有线网络
    var connType = val(d['if']);
    if (connType != null) {
      if (connType.toUpperCase().contains('WLAN') ||
          connType.toUpperCase().contains('WI-FI')) {
        connType = '无线网络 ($connType)';
      } else if (connType.contains('以太网') ||
          connType.toUpperCase().contains('ETHERNET')) {
        connType = '有线网络 ($connType)';
      }
    }
    return {
      'ip': val(d['ip']),
      'gw': val(d['gw']),
      'dns': val(d['dns']),
      'if': connType,
    };
  } catch (_) {
    return const {};
  }
}