I need a function that can return the number of packets received or loss percentage. Before I used the code below to get true/false if I receive any of the packets. This should work in Windows, but if somebody can do it suitable for Linux too, I would be thankful.
def ping_ip(ip):
current_os = platform.system().lower()
parameter = "-c"
if current_os == "windows":
parameter = "-n"
command = ['ping', parameter, '4', ip]
res = subprocess.call(command)
return res == 0
Here is my solution - just do stdout of ping command and analyze it.
def ping_ip(ip):
res = 0
current_os = platform.system().lower()
parameter = "-c"
if current_os == "windows":
parameter = "-n"
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
command = ['ping', parameter, '4', ip]
process = subprocess.Popen(command, startupinfo=si, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
percentage = 0
f = process.stdout.read().decode('ISO-8859-1').split()
for x in f:
if re.match(r".*%.*", x):
strArr = []
strArr[:0] = x
strArr = strArr[1:-1]
listToStr = ''.join(map(str, strArr))
percentage = int(listToStr)
if percentage == 0:
res = 0 # 0% loss
elif percentage == 100:
res = 1 # 100% loss
else:
res = 2 # partial loss
return res
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.