How to Check if Your System Has an Internet Connection Using Python?

Estimated read time 2 min read

To check if your system has an internet connection using Python, you can make a simple HTTP request to a reliable website and check the response. Here’s an example using the requests library:

import requests

def check_internet_connection():
    url = ""  # Website to check internet connection
        response = requests.get(url, timeout=5)
        response.raise_for_status()  # Check for any HTTP errors
        print("Internet connection is available.")
    except requests.exceptions.RequestException:
        print("No internet connection.")

# Example usage

In this example, the check_internet_connection function sends a GET request to Google’s homepage ( If the request is successful and doesn’t encounter any errors, it indicates that the system has an internet connection.

The requests.get() method is used to send the GET request, and the timeout parameter is set to 5 seconds to limit the waiting time for a response. The response.raise_for_status() method checks if there were any HTTP errors in the response.

If an internet connection is available, the message “Internet connection is available” is printed. Otherwise, the message “No internet connection” is printed.

Note: Make sure you have the requests library installed. You can install it using pip with the command pip install requests.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply