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


  • We imported http.client library.
  • Initialized URL as
  • 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 :


# importing required module
import http.client as httplib
# function to check internet connectivity
def checkInternetHttplib(url="", timeout=3):
    connection = httplib.HTTPConnection(url, timeout=timeout)
        # only header requested for fast operation
        connection.request("HEAD", "/")
        connection.close()  # connection closed
        print("Internet On")
        return True
    except Exception as exep:
        return False
checkInternetHttplib("", 3)


Internet On

Method 2: Using requests.get()


  • Importing the required requests module
  • Initializing URL to
  • 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”


# importing requests module
import requests
# initializing URL
timeout = 10
    # 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")


Internet is off

My Personal Notes arrow_drop_up
Recommended Articles
Page :