It seems I cannot get the urllib2 timeout to be taken into account. I did read - I suppose - all posts related to this topic and it seems I'm not doing anything wrong. Am I correct? Many thanks for your kind help.
Scenario:
I need to check for Internet connectivity before continuing with the remaining of a script. I then wrote a function (Net_Access), which is provided below.
- When I execute this code with my LAN or Wifi interface connected, and by checking an existing hostname: all is fine as there is no error or problem, thus no timeout.
- If I unplug my LAN connector or I check against a non-existent hostname, the timeout value seems to be ignored. What's wrong with my code please?
Some info:
- Ubuntu 10.04.4 LTS (running into a VirtualBox v4.2.6 VM, Host OS is MAC OS X Lion)
cat /proc/sys/kernel/osrelease: 2.6.32-42-generic- Python 2.6.5
My code:
#!/usr/bin/env python import socket import urllib2 myhost = 'http://www.google.com' timeout = 3 socket.setdefaulttimeout(timeout) req = urllib2.Request(myhost) try: handle = urllib2.urlopen(req, timeout = timeout) except urllib2.URLError as e: socket.setdefaulttimeout(None) print ('[--- Net_Access() --- No network access') else: print ('[--- Net_Access() --- Internet Access OK') 1) Working, with LAN connector plugged in
$ $ time ./Net_Access [--- Net_Access() --- Internet Access OK real 0m0.223s user 0m0.060s sys 0m0.032s 2) Timeout not working, with LAN connector unplugged
$ time ./Net_Access [--- Net_Access() --- No network access real 1m20.235s user 0m0.048s sys 0m0.060s Added to original post: test results (using IP instead of FQDN)
As suggested by @unutbu (see comments) replacing the FQDN in myhost with an IP address fixes the problem: the timeout is taken into effect.
LAN connector plugged in...
$ time ./Net_Access [--- Net_Access() --- Internet Access OK
real 0m0.289s user 0m0.036s sys 0m0.040s LAN connector unplugged...
$ time ./Net_Access [--- Net_Access() --- No network access
real 0m3.082s user 0m0.052s sys 0m0.024s This is nice, but it means that timeout could only be used with IP and not FQDN. Weird...
Did someone found a way to use urllib2 timeout without getting into pre-DNS resolution and pass IP to the function, or are you first using socket to test connection and then fire urllib2 when you are sure that you can reach the target?
Many thanks.
myhost = 'http://www.google.com'withmyhost = 'http://74.125.228.98'?socketto, say,('8.8.8.8', 53)or('74.125.228.98', 80)is much simpler.