Testing for Internet Connection

Alexnb alexnbryan at gmail.com
Tue Jul 15 18:00:35 CEST 2008




Troeger Thomas (Ext) wrote:
> 
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Thomas this code did not work on google.com and I also tried it with port
443
-- 
View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18468756.html
Sent from the Python - python-list mailing list archive at Nabble.com.




More information about the Python-list mailing list