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: response=urllib2.urlopen('http://18.104.22.168',timeout=1) return True except urllib2.URLError as err: pass return False
22.214.171.124 is one of the IP-addresses for google.com. Change
http://126.96.36.199 to whatever site can be expected to respond quickly.
Using a numerical IP-address avoids a DNS lookup, which may block the
urllib2.urlopen call for more than a second. Thanks to @rzetterberg for pointing this out.
By specifying the
timeout=1 parameter, the call to
urlopen will not take much longer than 1 second even if the internet is not "on".