3

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.

2
  • Does this post answer your question? Commented Feb 26, 2015 at 20:37
  • This post didn't answer my question I saw it already Commented Feb 26, 2015 at 20:40

5 Answers 5

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

can you explain this line you have added to function I used?
Why do you test it four times, each for five milliseconds longer?
1

You can also use another Library to do it. If you're pulling in any content I would highly suggest using Requests.

Joran has a great answer, it definitely works. Another approach is:

def checkNet():
    import requests
    try:
        response = requests.get("http://www.google.com")
        print "response code: " + response.status_code
    except requests.ConnectionError:
        print "Could not connect"

The benefit is you can use the response object and just continue on with your work (response.text etc..)

It's always faster to try it and handle the error if it breaks than do needless checks repeatedly.

Comments

0

I would suggest you to use urllib. Is a pre-installed library and you don't need to install extra library. That's my propose:

def isConnected():
    import urllib
    from urllib import request
    try:
        urllib.request.urlopen('http://google.com') # If you want you can add the timeout parameter to filter slower connections. i.e. urllib.request.urlopen('http://google.com', timeout=5)

        return True
    except:
        return False

Comments

0

Use this function to check internet availability

    def check_internet():
        os.system('ping -c1 github.com > rs_net 2>&1')
        if "0% packet loss" in open('rs_net').read():
            val = 1
        else:
            val = 0
        os.system('rm rs_net > /dev/null 2>&1')
        return val

    if check_internet() == 1:
        print("Connected to network") 

Comments

-1

I think this should work, Do this: Make a Def function and put this in it

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:
    print ("internet off.")

2 Comments

if I remove s.close() , would it work like a listener ?
Yeah It should work as a listener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.