Python Ping Ip Address with Results

Python Ping Ip Address with Results

I am using this code to verify the connection of an ip address using python and this code works for me. However, I would like to use this code to return a value if it has connectivity or not with the ip address. How should I do this?

the code here goes like this:

import subprocess
import platform 

ip_addr = '192.168.0.10'

def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if 
the host name is valid.
"""

# Option for the number of packets as a function of
   param = '-n' if platform.system().lower()=='windows' else '-c'

# Building the command. Ex: "ping -c 1 google.com"
   command = ['ping', param, '1', host]

   return subprocess.call(command) == 0



ping(ip_addr) 
2

1 Answer

If you need to capture the output, or just don't like the way you are doing it currently then you could capture stdout and check the output for a failure string. You can capture stdout like this:

def ping(host):
    param = '-n' if platform.system().lower()=='windows' else '-c'
    command = ['ping', param, '1', host]

    result = subprocess.run(command, stdout=subprocess.PIPE)
    output = result.stdout.decode('utf8')
    if "Request timed out." in output or "100% packet loss" in output:
        return "NOT CONNECTED"
    return "CONNECTED"

print(ping(ip_addr))
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.