Created
July 18, 2024 13:10
-
-
Save proteye/619af1aac22ba7d4230177ee0911af9c to your computer and use it in GitHub Desktop.
Check internet connection on Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:developer' as developer; | |
import 'dart:io'; | |
const _lookupHost = 'example.com'; | |
/// Web servers to check. | |
const _hosts = [ | |
'example.com', | |
'ya.ru', | |
'google.com', | |
]; | |
/// DNS servers to check. | |
const _dnsAddresses = [ | |
/// Yandex DNS server | |
'77.88.8.8', | |
'77.88.8.1', | |
/// Google DNS server | |
'8.8.8.8', | |
'8.8.4.4', | |
]; | |
/// Connection timeout. | |
const _timeout = Duration(seconds: 1); | |
/// Check Internet connection. | |
Future<bool> checkInternetConnection() async { | |
try { | |
final result = await InternetAddress.lookup(_lookupHost); | |
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { | |
// HTTP checking. | |
for (final host in _hosts) { | |
final address = (await InternetAddress.lookup(host)).first.address; | |
final result = await checkHostReachable(address, 80); | |
if (result) { | |
return true; | |
} | |
} | |
// DNS checking. | |
for (final address in _dnsAddresses) { | |
final result = await checkHostReachable(address, 53); | |
if (result) { | |
return true; | |
} | |
} | |
} | |
} on SocketException catch (_, stackTrace) { | |
developer.log( | |
'$_', | |
name: 'checkInternetConnection', | |
error: _, | |
stackTrace: stackTrace, | |
); | |
} | |
return false; | |
} | |
/// Is DNS server with [address] reachable? | |
Future<bool> checkHostReachable(String address, int port) async { | |
Socket? sock; | |
try { | |
sock = await Socket.connect( | |
InternetAddress( | |
address, | |
type: InternetAddressType.IPv4, | |
), | |
port, | |
timeout: _timeout, | |
) | |
..destroy(); | |
return true; | |
} catch (e) { | |
sock?.destroy(); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment