Reputation: 915
How do I check if a python3 module is connected to the internet?
I saw this is solution for Python2 and wanted to do something similar.
Upvotes: 1
Views: 9856
Reputation: 7
response = urlopen('https://www.google.com/', timeout=10)
print(response)
<http.client.HTTPResponse object at 0x0000024E196C9CC0>
so..
import sys
from urllib.request import urlopen
response = urlopen('https://www.google.com/', timeout=10)
if response == "<http.client.HTTPResponse object at 0x0000024E196C9CC0>":
print("Ok!")
else:
print("NO!!!")
Upvotes: -1
Reputation: 1
this is for python3 . I am using this for a while now.
import socket,time
mem1 = 0
while True:
try:
host = socket.gethostbyname("www.google.com") #Change to personal choice of site
s = socket.create_connection((host, 80), 2)
s.close()
mem2 = 1
if (mem2 == mem1):
pass #Add commands to be executed on every check
else:
mem1 = mem2
print ("Internet is working") #Will be executed on state change
except Exception as e:
mem2 = 0
if (mem2 == mem1):
pass
else:
mem1 = mem2
print ("Internet is down")
time.sleep(10) #timeInterval for checking
Upvotes: 0
Reputation: 1108
We use the following code to test the internet connection. Here generate_204 will generate code 204 when the internet is connected or else give errors.
import requests
url = 'http://clients3.google.com/generate_204'
try:
response = requests.get(url, timeout=5)
if response.status_code == 204:
print(response.status_code)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print("OOps: Something Else", err)
except requests.exceptions.HTTPError as errh:
print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
Upvotes: 0
Reputation: 697
You can check also only the hostname if is online: (useful is the url is an API and needs a POST, instead of a GET)
def have_internet(url):
try:
o = urlparse(url)
response = urlopen(o.scheme+'://'+o.netloc, timeout=5)
return True
except:
print('No access to',url)
return False
Upvotes: 0
Reputation: 915
The following snippet worked for me.
from urllib.request import urlopen
def internet_on():
try:
response = urlopen('https://www.google.com/', timeout=10)
return True
except:
return False
Improved error handling and/or other configurations might be required for other use cases.
Upvotes: 5