Python Program to Check Internet Connection
urllib.request.urlopen('http://google.com') inside a try-except block to catch errors if no connection is available.Examples
How to Think About It
Algorithm
Code
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()
Dry Run
Let's trace the program when internet is connected.
Start function
Call check_internet()
Try to open URL
urllib.request.urlopen('http://google.com', timeout=5) succeeds
Print success message
Print 'Internet is connected'
| Step | Action | Result |
|---|---|---|
| 1 | Call check_internet() | Function starts |
| 2 | Open URL http://google.com | Success |
| 3 | Print message | Internet 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
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()
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()
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| urllib.request | O(1) | O(1) | Simple HTTP check without extra libraries |
| socket connection | O(1) | O(1) | Fast low-level connectivity check |
| requests library | O(1) | O(1) | User-friendly HTTP check with more features |