How to check whether users internet is on or off using Python?
Many times while developing our projects we require a solution for checking whether the user system’s internet is on or off below are some simple solutions for checking that using Python. There are two ways in which this can be achieved:
Method 1: Using ‘httplib’
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Approach
- We imported http.client library.
- Initialized URL as www.geeksforgeeks.org
- We tried to establish a connection with the given URL.
- Requested only the header of Web Page for fast operations.
- True is returned if the connection is on and the message is displayed.
- An exception is caught if it’s not working and the error message is displayed.
Example :
Python3
# importing required moduleimport http.client as httplib # function to check internet connectivitydef checkInternetHttplib(url="www.geeksforgeeks.org", timeout=3): connection = httplib.HTTPConnection(url, timeout=timeout) try: # only header requested for fast operation connection.request("HEAD", "/") connection.close() # connection closed print("Internet On") return True except Exception as exep: print(exep) return False checkInternetHttplib("www.geeksforgeeks.org", 3) |
Output:
Internet On
Method 2: Using requests.get()
Approach
- Importing the required requests module
- Initializing URL to geeksforgeeks.org
- Initializing timeout to be 10
- Requesting the given URL.
- Printing “Internet is on” or going to generate exceptions.
- Catching exception and printing “Internet is off”
Python3
# importing requests moduleimport requests # initializing URLtimeout = 10try: # requesting URL request = requests.get(url, timeout=timeout) print("Internet is on") # catching exceptionexcept (requests.ConnectionError, requests.Timeout) as exception: print("Internet is off") |
Output:
Internet is off


