Testing for Internet Connection

Thomas Troeger thomas.troeger.ext at siemens.com
Tue Jul 15 12:55:43 CEST 2008


Alex Marandon wrote:
> Alexnb wrote:
>> I am wondering, is there a simple way to test for Internet connection? If
>> not, what is the hard way :p
> 
> Trying to fetch the homepage from a few major websites (Yahoo, Google, 
> etc.)? If all of them are failing, it's very likely that the connection 
> is down. You can use urllib2 [1] to accomplish that.
> 
> [1] <http://docs.python.org/lib/module-urllib2.html>

This seems to work and is rather fast and wastes no bandwidth:

==============================================================================
#!/usr/bin/python

import socket, struct

def check_host(host, port, timeout=1):
	"""
	Check for connectivity to a certain host.
	"""
	# assume we have no route.
	ret=False

	# connect to host.
	try:
		# create socket.
		sock=socket.socket()
		# create timeval structure.
		timeval=struct.pack("2I", timeout, 0)
		# set socket timeout options.
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeval)
		# connect to host.
		sock.connect((host, port))
		# abort communications.
		sock.shutdown(SHUT_RDWR)
		# we have connectivity after all.
		ret=True
	except:
		pass

	# try to close socket in any case.
	try:
		sock.close()
	except:
		pass

	return ret

# -------------------------------- main ---------------------------------

if check_host("www.heise.de", 80):
	print "Horray!"
else:
	print "We've lost headquarters!"
==============================================================================

I hope the code is ok, but there is always something you can do better. 
Comments? :)

Cheers,
Thomas.



More information about the Python-list mailing list