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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With