Checking internet connection with Python
Question:
I’m working on an application that uses internet so I need to check if there is an internet connection at the load of the application so I use this function:
def is_connected():
try:
print "checking internet connection.."
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print 'internet on.'
return True
except Exception,e:
print e
print "internet off."
return False
Sometimes it fails although there is an internet connection, it says ‘timed out’. I also tried using urllib2 to send a request to Google but it took time and timed out too. Is there a better way to do it? I’m using Windows 7 and Python 2.6.6.
Answers:
you should do something like
def check_internet():
for timeout in [1,5,10,15]:
try:
print "checking internet connection.."
socket.setdefaulttimeout(timeout)
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print 'internet on.'
return True
except Exception,e:
print e
print "internet off."
return False
or even better (mostly taken from other answer linked in comments)
def internet_on():
for timeout in [1,5,10,15]:
try:
response=urllib2.urlopen('http://google.com',timeout=timeout)
return True
except urllib2.URLError as err: pass
return False
You can also use another Library to do it. If you’re pulling in any content I would highly suggest using Requests.
Joran has a great answer, it definitely works. Another approach is:
def checkNet():
import requests
try:
response = requests.get("http://www.google.com")
print "response code: " + response.status_code
except requests.ConnectionError:
print "Could not connect"
The benefit is you can use the response object and just continue on with your work (response.text etc..)
It’s always faster to try it and handle the error if it breaks than do needless checks repeatedly.
I would suggest you to use urllib. Is a pre-installed library and you don’t need to install extra library.
That’s my propose:
def isConnected():
import urllib
from urllib import request
try:
urllib.request.urlopen('http://google.com') # If you want you can add the timeout parameter to filter slower connections. i.e. urllib.request.urlopen('http://google.com', timeout=5)
return True
except:
return False
I think this should work, Do this:
Make a Def function and put this in it
try:
print ("checking internet connection..")
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print ('internet on.')
return True
except Exception:
print ("internet off.")
Use this function to check internet availability
def check_internet():
os.system('ping -c1 github.com > rs_net 2>&1')
if "0% packet loss" in open('rs_net').read():
val = 1
else:
val = 0
os.system('rm rs_net > /dev/null 2>&1')
return val
if check_internet() == 1:
print("Connected to network")
I’m working on an application that uses internet so I need to check if there is an internet connection at the load of the application so I use this function:
def is_connected():
try:
print "checking internet connection.."
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print 'internet on.'
return True
except Exception,e:
print e
print "internet off."
return False
Sometimes it fails although there is an internet connection, it says ‘timed out’. I also tried using urllib2 to send a request to Google but it took time and timed out too. Is there a better way to do it? I’m using Windows 7 and Python 2.6.6.
you should do something like
def check_internet():
for timeout in [1,5,10,15]:
try:
print "checking internet connection.."
socket.setdefaulttimeout(timeout)
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print 'internet on.'
return True
except Exception,e:
print e
print "internet off."
return False
or even better (mostly taken from other answer linked in comments)
def internet_on():
for timeout in [1,5,10,15]:
try:
response=urllib2.urlopen('http://google.com',timeout=timeout)
return True
except urllib2.URLError as err: pass
return False
You can also use another Library to do it. If you’re pulling in any content I would highly suggest using Requests.
Joran has a great answer, it definitely works. Another approach is:
def checkNet():
import requests
try:
response = requests.get("http://www.google.com")
print "response code: " + response.status_code
except requests.ConnectionError:
print "Could not connect"
The benefit is you can use the response object and just continue on with your work (response.text etc..)
It’s always faster to try it and handle the error if it breaks than do needless checks repeatedly.
I would suggest you to use urllib. Is a pre-installed library and you don’t need to install extra library.
That’s my propose:
def isConnected():
import urllib
from urllib import request
try:
urllib.request.urlopen('http://google.com') # If you want you can add the timeout parameter to filter slower connections. i.e. urllib.request.urlopen('http://google.com', timeout=5)
return True
except:
return False
I think this should work, Do this:
Make a Def function and put this in it
try:
print ("checking internet connection..")
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print ('internet on.')
return True
except Exception:
print ("internet off.")
Use this function to check internet availability
def check_internet():
os.system('ping -c1 github.com > rs_net 2>&1')
if "0% packet loss" in open('rs_net').read():
val = 1
else:
val = 0
os.system('rm rs_net > /dev/null 2>&1')
return val
if check_internet() == 1:
print("Connected to network")