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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With