How to find out whether computer is connected to internet in python?
Asked
Active
Viewed 2,508 times
2 Answers
16
If you have python2.6 you can set a timeout. Otherwise the connection might block for a long time.
try:
urllib2.urlopen("http://example.com", timeout=2)
except urllib2.URLError:
# There is no connection

Nadia Alramli
- 111,714
- 37
- 173
- 152
-
1+1 for the timeout. As Gamecat said, it could also mean that example.com is down :-) – Vinay Sajip Aug 28 '09 at 12:17
-
11@Vinay, that's right. Maybe he should try google.com. If google was down. Then I guess there is no internet ;) – Nadia Alramli Aug 28 '09 at 12:19
-
1you can set a timeout in 2.5 as well using import socket; socket.setdefaulttimeout( – tgray Aug 28 '09 at 14:45
7
Try
import urllib
file = urllib.urlopen("http://stackoverflow.com/")
html = file.read()
and see if that works, or if it throws an exception. Even if you don't use the exact code, you should get the idea.

Vinay Sajip
- 95,872
- 14
- 179
- 191
-
2Lol, it only gives a false negative if SO is down ;-). Better check a couple of sites and assume connection if at least one is up. – Toon Krijthe Aug 28 '09 at 12:09
-
-
-
-
Plenty of tricky failure modes. I know an environment that will popup a dialog box warning you that the connection attempt has been logged, and please enter username+password to connect to stackoverflow.com. That's a system-modal dialog I think. – MSalters Aug 28 '09 at 15:29