Reputation: 667
I am trying to separate out the different types of errors that can occur when using Python's sockets
module to perform internet requests so that I can handle them appropriately. Particularly, the case when no internet connection is available, which I would like to handle so that I can check and wait for availability.
The requests I am dealing with are via URLs, at the core of which is socket
's getaddrinfo()
function, which, primarily, resolves a hostname to an IP. For remote hosts this involves a DNS query, which obviously does not work without the internet, and hence is the first point of failure if no internet connection is available.
However, it seems that getaddrinfo()
raises the same exception for both "no internet" (i.e. DNS query send failed or timed out) and a non-existent domain (i.e. internet is available and DNS query/answer completed) - and as a result I cannot detect the no internet condition that I need.
For example, running the following non-existent domain with an internet connection:
socket.getaddrinfo("www.thsidomaindoesntexist12309657.com", 80)
The resulting exception is:
socket.gaierror: [Errno 11001] getaddrinfo failed
Where errno 11001 corresponds to socket.EAI_NONAME
. This is the expected behaviour, since the domain actually does not exist.
Yet when I try the following existing domain with no internet connection (network adaptor disabled):
socket.getaddrinfo("www.google.com", 80)
I get exactly the same exception as before, apparently indicating that the domain does not exist (even though we can't know because we never got a DNS response).
How can I detect no internet connection when using sockets and getaddrinfo()
? Is it impossible, or is this a bug I am experiencing, or something else?
Upvotes: 0
Views: 690
Reputation: 123433
How can I detect no internet connection when using sockets and getaddrinfo()
You cannot get the information from getaddrinfo
. This functions is an abstract interface to name resolution which could be done against a local DNS server but is also often done against a DNS server in the local network. The function provides no information why it failed to resolve a name since it often has no idea itself why the resolving failed.
Apart from that even if the DNS lookup succeeds there is no guarantee that there is actually a working internet connection. It might be that the result of the DNS lookup is taken from cache or it might be that one could actually resolve the name but that the actual connection to the target (like a web server) is blocked by some firewall. It might also be that one gets an IP address but that it is the wrong one as is often the case with captive portals.
The common way to find out if there is a working internet connection is to contact a known good server with a specific request and check if the response is as expected.
Upvotes: 1