How can I see if there's an available and active network connection in Python?
networking, python
Solution
Perhaps you could use something like this:
from urllib import request
def internet_on():
try:
request.urlopen('http://216.58.192.142', timeout=1)
return True
except request.URLError as err:
return False
For Python 2.x replace the import statement by `import urllib2 as request`:
Currently, 8.8.8.8 is one of the IP addresses from Google. Change `http://8.8.8.8` to whatever site can be expected to respond quickly.
This fixed IP will not map to google.com forever. So this code is not robust -- it will need constant maintenance to keep it working.
The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to `urllib_request.urlopen` for more than a second. Thanks to @rzetterberg for pointing this out.
If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running
% dig google.com +trace
...
google.com. 300 IN A 216.58.192.142
Problem
I want to see if I can access an online API, but for that, I need to have Internet access. How can I see if there's a connection available and active using Python?