Skip to content

Instantly share code, notes, and snippets.

@proteye
Created July 18, 2024 13:10
Show Gist options
  • Save proteye/619af1aac22ba7d4230177ee0911af9c to your computer and use it in GitHub Desktop.
Save proteye/619af1aac22ba7d4230177ee0911af9c to your computer and use it in GitHub Desktop.
Check internet connection on Flutter
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