Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking internet connection with Python

Tags:

python

I'm working on an application that uses internet so I need to check if there is an internet connection at the load of the application so I use this function:

def is_connected():

    try:
        print "checking internet connection.."
        host = socket.gethostbyname("www.google.com")
        s = socket.create_connection((host, 80), 2)
        s.close()
        print 'internet on.'
        return True

    except Exception,e:
        print e
        print "internet off."
    return False

Sometimes it fails although there is an internet connection, it says 'timed out'. I also tried using urllib2 to send a request to Google but it took time and timed out too. Is there a better way to do it? I'm using Windows 7 and Python 2.6.6.

like image 752
oridamari Avatar asked Sep 19 '26 06:09

oridamari


1 Answers

you should do something like

def check_internet():
    for timeout in [1,5,10,15]:
        try:
            print "checking internet connection.."
            socket.setdefaulttimeout(timeout)
            host = socket.gethostbyname("www.google.com")
            s = socket.create_connection((host, 80), 2)
            s.close()
            print 'internet on.'
            return True

        except Exception,e:
            print e
            print "internet off."
    return False

or even better (mostly taken from other answer linked in comments)

def internet_on():
    for timeout in [1,5,10,15]:
        try:
            response=urllib2.urlopen('http://google.com',timeout=timeout)
            return True
        except urllib2.URLError as err: pass
    return False
like image 78
Joran Beasley Avatar answered Sep 20 '26 20:09

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!