How to Check Your Internet Connection in Python?

Problem Formulation and Solution Overview

In this article, you’ll learn how to check an Internet Connection in Python.

Problem: Given a Python program. You want to check if your computer currently has access to the Internet so you can do some follow-up work.

Example:

  • If your computer has access, you want to print "Success".
  • Otherwise, you want to print "Failure".

Specifically, how to implement the function has_connection() in the following sample code snippet?

if check_connection():
    print('Success!')
else:
    print('Failure!')

To make it more fun, we have the following running scenario:

Let’s assume you are a Python Coder working for AllTech. Lately, they have been having issues with their internet connections. You are tasked with writing code to check the connection and return a status/error message.

πŸ’¬ Question: How would we write Python code to check to see if an internet connection has been established?

We can accomplish this task by one of the following options:


Preparation

Before any data manipulation can occur, one (1) new library will require installation.

  • The Requests library allows access to its many methods and makes data manipulation a breeze!

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.


$ pip install requests

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

from urllib.request import urlopen as url
import requests
import socket 

Method 1: Use urlopen()

This example uses urlopen() to establish a connection to the URL shown below. In addition, two (2) parameters are passed: a valid URL and a timeout.

try:
    url('https://finxter.com/', timeout=3)
    print('Success')
except ConnectionError as e: 
    print(f'Failure - {e}')

This code is wrapped inside a try/except statement. When run, the code drops inside the try statement and checks to see if a connection can be established to the indicated URL. This attempt waits three (3) seconds before timing out.

Depending on the connection status, a message indicating the same is output to the terminal.

Output

Success

Method 2: Use requests.get()

This example requires the use of the requests library and uses requests.get() to establish a connection to the URL shown below. A status code returns indicating Success or Failure.

res = requests.get('https://finxter.com/')
print(res)

if (res.status_code):
    print('Success')
else:
    print('f'Failure')

This code accepts a URL and attempts to establish a connection to the same. The results of this connection save to res as an object.

<Response [200]>

This object must be referenced as indicated above to retrieve the status code. Then, the appropriate message is output to the terminal depending on this code.

Output

Success

Method 3: Use a Lambda

In the methods above, we used a few lines of code to establish a connection and display the appropriate result. This one-liner accomplishes the same task in one line!

# One-Liner to Check Internet Connection:
print((lambda a: 'Success' if 0 == a.system('ping finxter.com -w 4 > clear') else 'Failure')(__import__('os')))

This code pings the shown URL and, depending on the results, outputs the appropriate message to the terminal. The remarkable thing is how you can import a library on-the-fly!

Output

Success

Method 4: Use socket

This example requires the socket library and creates a function to establish a connection to the URL shown below. A Boolean value returns indicating True/False.

def check_connection():
    try:
        host = socket.gethostbyname('www.google.com')
        s = socket.create_connection((host, 80), 2)
        return True
    except:
        return False 

res = check_connection()
print(res)

This code defines a new function, check_connection. Using a try/except statement attempts to connect to the indicated URL. Depending on the result, the function returns either True or False.

Finally, the function is called, the code runs, and the result outputs to the terminal.

Output

True

Summary

These four (4) methods to check the internet connection should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!