Skip to content
Related Articles

Related Articles

Improve Article

How to check whether users internet is on or off using Python?

  • Last Updated : 11 Dec, 2020

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 module
import http.client as httplib
  
  
# function to check internet connectivity
def 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 module
import requests
  
# initializing URL
timeout = 10
try:
    # requesting URL
    request = requests.get(url, timeout=timeout)
    print("Internet is on")
  
# catching exception
except (requests.ConnectionError, requests.Timeout) as exception:
    print("Internet is off")

Output:

Internet is off



My Personal Notes arrow_drop_up
Recommended Articles
Page :