Asked By – aF.
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?
Now we will see solution for issue: How can I see if there’s an available and active network connection in Python?
Perhaps you could use something like this:
import urllib2 def internet_on(): try: urllib2.urlopen('http://184.108.40.206', timeout=1) return True except urllib2.URLError as err: return False
Currently, 220.127.116.11 is one of the IP addresses for google.com. Change
http://18.104.22.168 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 22.214.171.124