0
0
PythonProgramBeginner · 2 min read

Python Program to Check Internet Connection

You can check internet connection in Python by trying to open a website using urllib.request.urlopen('http://google.com') inside a try-except block to catch errors if no connection is available.
📋

Examples

InputInternet is connected
OutputInternet is connected
InputInternet is disconnected
OutputNo internet connection
InputSlow or no response from website
OutputNo internet connection
🧠

How to Think About It

To check internet connection, the program tries to reach a well-known website like Google. If it can open the website without error, the internet is working. If it cannot, it means there is no connection or the website is unreachable.
📐

Algorithm

1
Try to open a connection to a reliable website (e.g., http://google.com).
2
If the connection opens successfully, print 'Internet is connected'.
3
If an error occurs (like timeout or no response), print 'No internet connection'.
💻

Code

python
import urllib.request

def check_internet():
    try:
        urllib.request.urlopen('http://google.com', timeout=5)
        print('Internet is connected')
    except:
        print('No internet connection')

check_internet()
Output
Internet is connected
🔍

Dry Run

Let's trace the program when internet is connected.

1

Start function

Call check_internet()

2

Try to open URL

urllib.request.urlopen('http://google.com', timeout=5) succeeds

3

Print success message

Print 'Internet is connected'

StepActionResult
1Call check_internet()Function starts
2Open URL http://google.comSuccess
3Print messageInternet is connected
💡

Why This Works

Step 1: Try to open a website

The program uses urllib.request.urlopen to try opening a connection to a website. This tests if the internet is reachable.

Step 2: Handle errors

If opening the URL fails, an exception is raised. The except block catches this to handle no connection.

Step 3: Print result

If no error occurs, it prints 'Internet is connected'. Otherwise, it prints 'No internet connection'.

🔄

Alternative Approaches

Using socket to connect to DNS server
python
import socket

def check_internet_socket():
    try:
        socket.create_connection(('8.8.8.8', 53), timeout=5)
        print('Internet is connected')
    except OSError:
        print('No internet connection')

check_internet_socket()
This method tries to connect to Google's DNS server using sockets, which can be faster and does not require HTTP.
Using requests library
python
import requests

def check_internet_requests():
    try:
        requests.get('http://google.com', timeout=5)
        print('Internet is connected')
    except requests.RequestException:
        print('No internet connection')

check_internet_requests()
This method uses the popular requests library for HTTP requests, which is more user-friendly but requires installing the library.

Complexity: O(1) time, O(1) space

Time Complexity

The program performs a single network request, so time is constant and depends on network speed, not input size.

Space Complexity

The program uses a fixed amount of memory for the request and error handling, so space is constant.

Which Approach is Fastest?

Using socket connection is usually faster than HTTP requests because it avoids full HTTP handshake, but less informative.

ApproachTimeSpaceBest For
urllib.requestO(1)O(1)Simple HTTP check without extra libraries
socket connectionO(1)O(1)Fast low-level connectivity check
requests libraryO(1)O(1)User-friendly HTTP check with more features
💡
Use a short timeout to avoid waiting too long when checking internet connection.
⚠️
Beginners often forget to set a timeout, causing the program to hang if the internet is down.