Just check a google server
1
2
3
4
5
6
7
|
importurllib2
definternet_on():
try:
returnTrue
excepturllib2.URLError aserr:pass
returnFalse
|
74.125.228.100 is one of the IP-addresses for google.com. Change http://74.125.228.100 to whatever site can be expected to respond quickly.
Using a numerical IP-address avoids a DNS lookup, which may block the urllib2.urlopen call for more than a second.
Thanks to @rzetterberg for pointing this out.
By specifying the timeout=1 parameter, the call to urlopen will not take much longer than 1 second even if the internet is not “on”.
Good Luck
Leave a comment