Tag: Python

Python Internet availability

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.


import random
import os
import socket
import subprocess

def getInternetStatusByDnsServers():
    r = ‘0’
    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:
    return r