How to Check if an IP is Up or Down in Python?

Estimated read time 2 min read

To check if an IP address is up or down in Python, you can use the ping command and execute it from within your Python script using the subprocess module. Here’s an example:

import subprocess

def check_ip_status(ip_address):
    try:
        output = subprocess.check_output(["ping", "-c", "1", ip_address])
        return True  # IP address is up
    except subprocess.CalledProcessError:
        return False  # IP address is down

ip = "192.168.1.1"
status = check_ip_status(ip)
if status:
    print(f"The IP address {ip} is up.")
else:
    print(f"The IP address {ip} is down.")

In the example above, we define the function check_ip_status() that takes an IP address as input and uses the subprocess module to execute the ping command with the specified IP address. If the ping command succeeds (exit status 0), it means the IP address is up, and the function returns True. Otherwise, if the ping command fails (non-zero exit status), it means the IP address is down, and the function returns False.

You can call the check_ip_status() function with the IP address you want to check, and it will return the corresponding status. Finally, you can use an if statement to print the appropriate message based on the returned status.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply