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
- 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.
Method 2: Using requests.get()
- 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”
Internet is off