Flutter app on iOS when on mobile data throws the following error:
SocketException: Failed host lookup: 'google.com' (OS Error: nodename nor servname provided, or not known, errno = 8)
when running the following code:
try {
final result = await InternetAddress.lookup('google.com',
type: InternetAddressType.IPv4);
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
hasConnection = true;
} else {
hasConnection = false;
}
} on SocketException catch (_) {
hasConnection = false;
}
App on Android or iOS with WiFi works well. Tested on two real devices.
The problem was on the parameter type: InternetAddressType.IPv4
. This requires that the returned address is only of type IPv4, which may not be the case for devices that are connected to the internet using IPv6. Using the default parameter (type: InternetAddressType.any
) solves the problem