HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Example Code to Check Internet Connection

Checking internet connectivity is a common requirement in many applications. Whether you’re developing a web app or a desktop program, knowing if the user has internet access is crucial.

Python offers simple methods to perform this check. One way is to use the `socket` module to test a connection to a well-known server. Another method is to use the `requests` library to send an HTTP request and check the response. Both approaches are effective and straightforward.

Method 1: Using socket

Let’s look at a simple Python code example to check if you have an internet connection.

import socket

def check_internet_connection():
try:
# Connect to a well-known website
socket.create_connection(("www.google.com", 80))
return True
except OSError:
return False

# Example usage
if check_internet_connection():
print("Internet is connected.")
else:
print("No internet connection.")

Now, let’s break down this code step-by-step:

1. Import the `socket` Module

  • `import socket`: This line imports Python’s `socket` module, which provides functions to work with network connections.

2. Define a Function `check_internet_connection`

  • `def check_internet_connection():`: This defines a function named `check_internet_connection` that we’ll use to check for an internet connection.

3. Try to Create a Connection

  • `try:`: This starts a block of code that might cause an error (exception). If an error happens, the code inside `except` will run.
    `socket.create_connection((“www.google.com”, 80))`: This line tries to establish a connection to Google’s server on port 80 (HTTP). If it succeeds, it means you have an internet connection.

4. Return `True` If Connection Succeeds

  • `return True`: If `socket.create_connection` is successful, this line is executed, and the function returns `True`, indicating that there is an internet connection.

5. Handle Exceptions (Errors)

  • `except OSError:`: This block catches an `OSError`, which happens if the connection attempt fails (e.g., no internet).
  • `return False`: If an exception occurs, this line returns `False`, indicating that there is no internet connection.

6. Example Usage

  • `if check_internet_connection():`: This line calls the `check_internet_connection` function and checks if it returns `True`.
  • `print(“Internet is connected.”)`: If the function returns `True`, this message is printed.
  • `else:`: If the function returns `False` (no internet), the following code is executed.
  • `print(“No internet connection.”)`: This message is printed if there is no internet connection.

Summary

  • Step 1: Import the `socket` module.
  • Step 2: Define a function to check the connection.
  • Step 3: Attempt to connect to a known server.
  • Step 4: Return `True` if the connection is successful.
  • Step 5: Catch errors and return `False` if connection fails.
  • Step 6: Use the function to check the internet and print the result.

This code is a straightforward way to determine if your device is connected to the internet by trying to reach a reliable website.

Method #2: Using requests

Another common method to check for an internet connection is by using the `requests` library to make a simple HTTP request to a known server.

Let’s see how you can do it.

import requests

def check_internet_connection():
try:
# Send a GET request to a reliable website
response = requests.get("https://www.google.com", timeout=5)
# Check if the response status code is 200 (OK)
if response.status_code == 200:
return True
except requests.ConnectionError:
return False

# Example usage
if check_internet_connection():
print("Internet is connected.")
else:
print("No internet connection.")

Step-by-Step Explanation

1. Import the `requests` Library

  • `import requests`: This line imports the `requests` library, which is used for making HTTP requests. It needs to be installed first using `pip install requests`.

2. Define a Function `check_internet_connection`

  • `def check_internet_connection():`: This defines a function named `check_internet_connection` to handle the check for an internet connection.

3. Try to Make an HTTP Request

  • `try:`: This starts a block of code that might throw an exception. If an error occurs, the code inside `except` will run.
  • `response = requests.get(“https://www.google.com”, timeout=5)`: This line sends a GET request to Google’s website. The `timeout=5` parameter means it will wait up to 5 seconds for a response before giving up.

4. Check Response Status Code

  • `if response.status_code == 200:`: This line checks if the server responded with a status code of 200, which means the request was successful.
  • `return True`: If the status code is 200, the function returns `True`, indicating that there is an internet connection.

5. Handle Exceptions

  • `except requests.ConnectionError:`: This block catches a `ConnectionError`, which occurs if the HTTP request fails (e.g., no internet connection).
  • `return False`: If a `ConnectionError` is caught, this line returns `False`, indicating there is no internet connection.

6. Example Usage

  • `if check_internet_connection():`: This line calls the `check_internet_connection` function and checks if it returns `True`.
  • `print(“Internet is connected.”)`: If the function returns `True`, this message is printed.
  • `else:`: If the function returns `False` (no internet), the following code is executed.
  • `print(“No internet connection.”)`: This message is printed if there is no internet connection.

Summary

  • Step 1: Import the `requests` library.
  • Step 2: Define a function to check the connection.
  • Step 3: Attempt to make an HTTP request to a reliable server.
  • Step 4: Return `True` if the response status code is 200.
  • Step 5: Catch connection errors and return `False` if the request fails.
  • Step 6: Use the function to check the internet and print the result.

This method uses HTTP requests to determine if the internet is available and is effective for checking connectivity in scenarios where you need to ensure the server is reachable.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Define Methods in a Class
Up Next
Example Python Code to Send an Email
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.