Posted By: Anonymous
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?
Perhaps you could use something like this:
import urllib2 def internet_on(): try: urllib2.urlopen('http://188.8.131.52', timeout=1) return True except urllib2.URLError as err: return False
Currently, 184.108.40.206 is one of the IP addresses for google.com. Change
http://220.127.116.11 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 18.104.22.168