
Python Internet availability
This Python code snippet gives you a solution when you need to check if your Python application can reach the Internet. You can always check if an Internet website is responding with urllib.request.urlretrieve. For instance, www.google.com. I have found this is not always reliable or even lock up the program.
A more reliable method is pinging one or more public DNS servers. This snippet is a Python 3 function that does just that. The function checks at random the set of DNS servers in the ‘li’ list and return ‘1’ when a DNS server responds or ‘0’ when all DNS severs fail.
function
import random
import os
import socket
import subprocess
def getInternetStatusByDnsServers():
r = ‘0’
li = ["8.8.8.8",\
"8.8.4.4",\
"209.244.0.3",\
"209.244.0.4",\
"208.67.222.222",\
"37.235.1.174",\
"91.239.100.100"\
]
random.shuffle(li)
for i in range(len(li)):
try :
hostname = li[i]
p = subprocess.Popen(["/bin/ping", "-c1", "-W1", hostname], stdout=subprocess.PIPE).stdout.read()
for item in str(p).split("\n"):
if "0% packet loss" in item:
return ‘1’
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
return r