How to check whether user's internet is on or off using Python?


Generally, if you need to verify whether your current system is connected to the internet or not, we can do so, by simply sending request to any of webserver application using the browser or, using the dos command ping.

The ping command is typically used to troubleshoot connectivity, reachability, and name resolution.

Similarly, in Python we can verify the user’s internet connectivity status either by sending a request to any web application or by using the ping command.

Using the request.get() method

In python, the modules request helps us to send HTTP requests using Python. By sending requests to any website using the methods of this module we can determine whether the user’s internet is on or off.

The get() method of the Python request module, accepts an URL as a parameter, and sends a GET request to the specified URL.

Syntax

The following is the syntax of the get() function –

requests.get(link, timeout)

Where,

  • link is the link of the webpage

  • timeout is the waiting time to listen the response from the DNS server.

If we try to send request without having the internet connection, this method generates an exception.

Example

In this example, by passing the website link to the get() function we are trying to determine whether the current system is connected to internet or not.

import requests
def internet_connection():
    try:
        response = requests.get("https://dns.tutorialspoint.com", timeout=5)
        return True
    except requests.ConnectionError:
        return False    
if internet_connection():
    print("The Internet is connected.")
else:
    print("The Internet is not connected.")

Output

The Internet is connected.

Using the socket.connect () method

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. We use the socket module in python to create and use sockets.

The connect() method of the socket module is used to establish a connection to a remote socket at address. If the current system doesn’t connect to the internet, this method generates an exception.

Example

Let’s see an example to check the connectivity of the users internet using the socket module’s connect() function.

import socket
def check_internet_connection():
    remote_server = "www.google.com"
    port = 80
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5)
    try:
        sock.connect((remote_server, port))
        return True
    except socket.error:
        return False
    finally:
        sock.close()
if check_internet_connection():
    print("Internet is connected.")
else:
    print("Internet is not connected.")

Output

Internet is not connected.

Using the urllib.request.urlopen() method

Similar to the above two libraries Python has an extensible library named urllib.request. Using the functions and classes of this module we can send request to desired URLs.

The urllib.request.urlopen() function is accepts an URL (as one of its parameters) and opens the connection to the specified URL. Similar to the above two methods if we execute this method without connecting to the internet this function generates an exception.

Example

Following is an example to check the connectivity of the users internet is using the urllib.request module. Here we are using the urlopen() function to open the specified website and check the internet status of the user.

import urllib.request
def check_internet_connection():
    try:
        urllib.request.urlopen("https://www.Tutorialspint.com")
        return True
    except urllib.error.URLError:
        return False

if check_internet_connection():
    print("Internet is connected.")
else:
    print("Internet is not connected.")

Output

Internet is not connected.

Using the ping command

To check the internet connectivity of the user is on or off we can also use the ping command, it is typically used to send the Internet control Message Protocol(ICMP) echo request to the remote server and then checks for the response, if it is received or not.

Using the subprocess module, we can start a new application from the current Python program. We can get the output of a program, command using the check_output() method. We can execute the ping command using this method and, determine whether the current system is connected to internet.

Example

This can be done by importing the subprocess module. In subprocess we have the function check_output() which checks for the internet status. The below is the code.

import subprocess
def check_internet_connection():
   try:
      subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])
      return True
   except subprocess.CalledProcessError:
      return False
if check_internet_connection():
   print("Internet is connected.")
else:
   print("Internet is not connected.")

Output

Following is the output of the above code, when we run the code -

Internet is not connected.

Updated on: 09-Aug-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements