Last modified: Feb 15, 2023 By Alexander Williams

Python: Check internet connection

Python programing has many libraries and modules to check the internet connection status.

In this tutorial, we'll use two methods to check the internet connection the requests library and the urllib module. Also, we'll learn how to wait for the internet connection.

If you are ready, let's get started.

Check internet connection using requests

First of all, we need to install requests.

If you don't know about requests, check out w3chool-requests.

installation via pip:

pip install requests

First, let's write our code then explain how it works.


import requests

timeout = 1

try:
    requests.head("http://www.google.com/", timeout=timeout)
    # Do something
    print('The internet connection is active')
except requests.ConnectionError:
    # Do something
    print("The internet connection is down")

Initially, we import requests. Next, we try to send a request to google.com usingrequests.head() method.

If the request returns ConnectionError that means the internet connection is down, and if not, that means our internet is active.

timeout: wait (seconds) for the client to make a connection or send a response.

Let"s write our code as a function:


def is_cnx_active(timeout):
    try:
        requests.head("http://www.google.com/", timeout=timeout)
        return True
    except requests.ConnectionError:
        return False

The is_cnx_active function return True or False.

Check internet connection using urllib.request.urlopen

With the urlopen function, we can also check the internet connection.

Let's see an example:


from urllib.request import urlopen

def is_cnx_active(timeout):
    try:
        urlopen('http://www.google.com', timeout)
        return True
    except: 
        return False

I think everything is clear, and no need to repeat the explanation.

How to wait for the internet connection

To wait for the internet connection, we'll use while True statement with the is_cnx_active() function.


while True:
    if is_cnx_active() is True:
        # Do somthing
        print("The internet connection is active")
        break
    else:
        pass


while True: loop forever.

The loop will break if is_cnx_active() returns True.