Python - How to build a good function to check for internet?

Asked

Viewed 2,017 times

4

The idea is to build a small function to check if there is an internet connection. I have a draft of a function that uses the library socket, but I do not believe that this is the most efficient way or one that best respects good programming practice.

from socket import gethostbyname,create_connection

# Verifica se esta conectado a internet
def conectadoInternet():

    tentativas = 0
    servidorRemoto = 'www.google.com'

    while tentativas < 3:
        if tentativas == 1:
            servidorRemoto = 'www.lds.org'
        elif tentativas == 2:
            servidorRemoto = 'www.msn.com'

        try:
            host = gethostbyname(servidorRemoto)
            s = create_connection((host, 80), 2)
            return True
        except: tentativas += 1

    return False

What would be other better ways?

2 answers

4


There is not only one correct answer

First you must understand what it means internet, in the concept of its application/program. Hence, implement applications to verify by the services (quality and bandwidth) that are important to you, in the acceptable standards. 1

Here, I think we’re just talking about synchronous solutions, like your.

Asynchronous outputs may be more interesting, mainly to scripts.

I find your solution one of the best, although a list containing the hosts is preferable, this should have a good performance at runtime. 4

But I don’t see a problem with:

import os
is_connected = (os.system('nc -z 8.8.8.8 53') == 0)

Or using requests.. 6 7

1

Hello, you can use the following code that attempts a connection to the google IP if the ip does not work, just use the ping command and the google url to get an updated ip

import urllib2

def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except urllib2.URLError as err: 
        return False

Browser other questions tagged

You are not signed in. Login or sign up in order to post.