If you are looking for the quickest, most efficient and proper way to ping or check IPs using Python 3 so this short tutorial is for you. This will work for both online or local hosts’ IPs, it just use the default ping command of the OS, so it doesn’t need any external module and it is still the most efficient way to do the task.

Import the required modules

Import the required modules as following:

1
2
3
4
import threading
import platform
import subprocess
import ipaddress

Divide the work in functions

The logic of the work is to check the IP in a thread then wait 1 seconds to run another thread and keep doing so in an infinite loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def check_ip(ip):
    try:
        ipaddress.ip_address(self.ip.text())
        print("Checking IP: {}".format(ip))
        print(f'{ip} is {"online" if ping_ip(ip) else "offline"}')
        threading.Timer(1, check_ip, args=(ip)).start()
    except ValueError:
        print("Invalid IP")
        return
    

def ping_ip(ip):
    return subprocess.call(['ping', '-n' if platform.system().lower() == 'windows' else '-c', '1', ip],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE) == 0

Now to check any IP for an infinite time, just call check_ip(IP)