We will take a look at the different methods using which one can check from internet connection using Python In Windows, Linux or MAC.
We will use socket to check internet connection. The given code will check for internet once, only when the function is called.
Let's First Look at the code and then will explain each line of code.
import socket def check_internet(): try: socket.create_connection(("18.104.22.168" ,53)) return True except OSError: pass return False print(check_internet())
The first line just imports socket package. Then we define a function named check_internet that uses a try/catch block to work.
We try to create a connection using socket.create_connection that takes host and port as s tuple. Then we can pass additional parameters like timeout in this case.
If the connection is successful, then we simply return True, indicating that an internet connection is present else when we encounter an OSError, we simply return False indicating that no internet connection is present.
For Better functionality and relaibility, you should use your own domain's host.
The approach here will be little different, but we will be simply extending the above code to get our job done. let's first look at the code and then we will explain it.
from multiprocessing import Process import socket import time def check_internet(): while True: time.sleep(1) try: socket.create_connection(("22.214.171.124" ,53)) print("Available...") except OSError: print("Disconnected...") return if __name__ == '__main__': new_process = Process(target = check_internet) new_process.start() new_process.join()
In the first three lines we import multiprocessing, socket and time packages.
we again define the check_internet function, and in there we use an infinite while loop to run the code continuously. But there, instead of actually running the code continuously, we are using time.sleep to stop the process for some given time so as to throttke down CPU usage. we use the same create_connection method from socket library to check internet.
NOTE : The time.sleep method accepts parameter in seconds. To pass 100 milliseconds use 0.1.
In the last 4 lines, we check if the current module is run directly. If yes then we run the function as a Process.You can learn more about multiprocessing here.