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?
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?
You can just try to download data, and if connection fail you will know that somethings with connection isn't fine.
Basically you can't check if computer is connected to internet. There can be many reasons for failure, like wrong DNS configuration, firewalls, NAT. So even if you make some tests, you can't have guaranteed that you will have connection with your API until you try.
Perhaps you could use something like this:
import urllib2
def internet_on():
try:
response=urllib2.urlopen('http://google.com',timeout=1)
return True
except urllib2.URLError as err: pass
return False
Change http://google.com
to whatever site can be expected to respond quickly.
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".
Try the operation you were attempting to do anyway. If it fails python should throw you an exception to let you know.
To try some trivial operation first to detect a connection will be introducing a race condition. What if the internet connection is valid when you test but goes down before you need to do actual work?