josh josh - 1 month ago 6
Python Question

Test if an internet connection is present in python

I have the following code that checks if an internet connection is present.

import urllib2

def internet_on():
try:
response=urllib2.urlopen('http://74.125.228.100',timeout=20)
return True
except urllib2.URLError as err: pass
return False


This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

Answer

My approach would be something like this:

import socket
REMOTE_SERVER = "www.google.com"
def is_connected():
  try:
    # see if we can resolve the host name -- tells us if there is
    # a DNS listening
    host = socket.gethostbyname(REMOTE_SERVER)
    # connect to the host -- tells us if the host is actually
    # reachable
    s = socket.create_connection((host, 80), 2)
    return True
  except:
     pass
  return False
print is_connected()

This will return within less than a second if there is no connection (OSX, Python 2.7).

Note: This test can return false positives -- e.g. the DNS lookup may return a server within the local network. To be really sure you are connected to the internet, and talking to a valid host, be sure to use more sophisticated methods (e.g. SSL).