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.