How to check whether user\'s internet is on or off using Python?

When building Python applications, you often need to verify whether the user's system has an active internet connection. This can be accomplished through several approaches: sending HTTP requests, establishing socket connections, or using system ping commands.

Using requests.get() Method

The requests module provides a simple way to send HTTP requests. By attempting to connect to a reliable website, we can determine internet connectivity ?

Syntax

requests.get(url, timeout=seconds)

Where url is the website URL and timeout is the maximum waiting time for a response.

Example

import requests

def check_internet_requests():
    try:
        response = requests.get("https://www.google.com", timeout=5)
        return True
    except requests.ConnectionError:
        return False

if check_internet_requests():
    print("Internet is connected.")
else:
    print("Internet is not connected.")
Internet is connected.

Using socket.connect() Method

Sockets provide low-level network communication. The connect() method attempts to establish a connection to a remote server ?

Example

import socket

def check_internet_socket():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        sock.connect(("8.8.8.8", 53))  # Google's DNS server
        sock.close()
        return True
    except socket.error:
        return False

if check_internet_socket():
    print("Internet is connected.")
else:
    print("Internet is not connected.")
Internet is connected.

Using urllib.request.urlopen() Method

The urllib.request module is Python's built-in HTTP client library. It can open URLs and handle various protocols ?

Example

import urllib.request
import urllib.error

def check_internet_urllib():
    try:
        urllib.request.urlopen("https://www.google.com", timeout=5)
        return True
    except urllib.error.URLError:
        return False

if check_internet_urllib():
    print("Internet is connected.")
else:
    print("Internet is not connected.")
Internet is connected.

Using Ping Command

The ping command sends ICMP echo requests to test network connectivity. Using subprocess, we can execute system commands from Python ?

Example

import subprocess
import platform

def check_internet_ping():
    param = "-n" if platform.system().lower() == "windows" else "-c"
    try:
        subprocess.check_output(["ping", param, "1", "8.8.8.8"], 
                              stderr=subprocess.STDOUT, timeout=5)
        return True
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
        return False

if check_internet_ping():
    print("Internet is connected.")
else:
    print("Internet is not connected.")
Internet is connected.

Comparison

Method Pros Cons Best For
requests Simple, handles HTTP protocols External dependency Web applications
socket Built-in, fast, low-level More complex Network applications
urllib Built-in, standard library Less feature-rich Simple HTTP checks
ping System-level, reliable Platform-dependent Network diagnostics

Conclusion

Use requests.get() for web applications, socket.connect() for fast low-level checks, or ping for system-level diagnostics. All methods use try-except blocks to handle connection failures gracefully.

Updated on: 2026-03-27T11:40:29+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements