views:

119

answers:

4

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?

A: 

Why don't you just try to connect and wait for the timeout?

Daren Thomas
my problem is how can I know that gave timeout for me to not put that code
aF
+5  A: 

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.

Tomasz Wysocki
"It's easier to ask for forgiveness than permission"
cobbal
this doesn't need to be that good. I simply need to try to connect to a site or ping something and if it gives timeout voilá. How can I do that?
aF
Is there any reason you can't just try to connect to API? Why you must to check it before real connection?
Tomasz Wysocki
I make an html page using python. The html page deppends on the arguments that I give in the python program. I only need to put some html code if I can access to the api. That's why I need to know before.
aF
+3  A: 

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".

unutbu
thanks m8, simple as that and it works very weel! :)
aF
+1  A: 

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?

mluebke