我有一个问题与提出的解决方案,使用查找并不总是返回预期的值。
这是由于DNS缓存,调用的值被缓存,而不是在下一次尝试时进行正确的调用,它会返回缓存的值。当然,这是一个问题,因为这意味着如果你失去了连接和调用查找,它仍然可以返回缓存的值,就像你有互联网一样,相反,如果你重新连接你的互联网后,查找返回null,它仍然会在缓存的持续时间内返回null,这可能是几分钟,即使你现在有互联网。
查找返回一些东西并不一定意味着你有网络,它不返回任何东西并不一定意味着你没有网络。它不可靠。
我从data_connection_checker插件中获得灵感,实现了以下解决方案:
/// If any of the pings returns true then you have internet (for sure). If none do, you probably don't.
Future<bool> _checkInternetAccess() {
/// We use a mix of IPV4 and IPV6 here in case some networks only accept one of the types.
/// Only tested with an IPV4 only network so far (I don't have access to an IPV6 network).
final List<InternetAddress> dnss = [
InternetAddress('8.8.8.8', type: InternetAddressType.IPv4), // Google
InternetAddress('2001:4860:4860::8888', type: InternetAddressType.IPv6), // Google
InternetAddress('1.1.1.1', type: InternetAddressType.IPv4), // CloudFlare
InternetAddress('2606:4700:4700::1111', type: InternetAddressType.IPv6), // CloudFlare
InternetAddress('208.67.222.222', type: InternetAddressType.IPv4), // OpenDNS
InternetAddress('2620:0:ccc::2', type: InternetAddressType.IPv6), // OpenDNS
InternetAddress('180.76.76.76', type: InternetAddressType.IPv4), // Baidu
InternetAddress('2400:da00::6666', type: InternetAddressType.IPv6), // Baidu
];
final Completer<bool> completer = Completer<bool>();
int callsReturned = 0;
void onCallReturned(bool isAlive) {
if (completer.isCompleted) return;
if (isAlive) {
completer.complete(true);
} else {
callsReturned++;
if (callsReturned >= dnss.length) {
completer.complete(false);
}
}
}
dnss.forEach((dns) => _pingDns(dns).then(onCallReturned));
return completer.future;
}
Future<bool> _pingDns(InternetAddress dnsAddress) async {
const int dnsPort = 53;
const Duration timeout = Duration(seconds: 3);
Socket socket;
try {
socket = await Socket.connect(dnsAddress, dnsPort, timeout: timeout);
socket?.destroy();
return true;
} on SocketException {
socket?.destroy();
}
return false;
}
对_checkInternetAccess的调用最多需要一个超时时间才能完成(这里是3秒),如果我们可以到达任何一个DNS,它将在到达第一个DNS时立即完成,而不需要等待其他DNS(因为到达一个DNS就足以知道您有internet)。所有对_pingDns的调用都是并行完成的。
它似乎在IPV4网络上工作得很好,当我不能在IPV6网络上测试它时(我没有访问IPV6网络),我认为它仍然可以工作。它也适用于发布模式构建,但我还必须将我的应用提交给苹果,看看他们是否发现了这个解决方案的任何问题。
它也应该在大多数国家(包括中国)工作,如果它不能在一个工作,你可以添加一个DNS到列表中,可以从你的目标国家访问。