Pythong: Get Ping Time - using pythonping module

Viewed 192

I need to ping IPs and return 2 pieces of info: success and average ping time.

Using the pythonping module I figure I can determine success if packets lost == 0 then it succeeded. Please let me know if I'm wrong or if there's a better way.

As for getting the average ping time, I'm lost on this. If you know, please let me know. Thanks.

Here's what I have.

Thanks.

from pythonping import ping

# The IP, Timeout Seconds
result = ping('2.255.250.65', count=1)
print('result.packets_lost ' + str(result.packets_lost))

if result.packets_lost == 0:
    print('success')
    # Need to get the average ping time here
    print(avg ping time)

else:
    print('failed')
    print(-1)
1 Answers

To know if a ping was successful, you can simply call the success method of the object pythonping.ping returns (an pythonping.executor.ResponseList inctance). Quote from running help(pythonping.ping("someip", count=10)):

success(self, option=<SuccessOn.One: 1>)
     Check success state of the request.

     :param option: Sets a threshold for success sign. ( 1 - SuccessOn.One, 2 - SuccessOn.Most, 3 - SuccessOn.All )
     :type option: int
     :return: Whether this set of responses is successful

And I guess ResponseList.rtt_avg_ms already contains the average time of the ping requests in milliseconds, though I could not find any documentation to prove this. Your final code could look like this:

from pythonping import ping

# The IP, Timeout Seconds
result = ping('2.255.250.65', count=1)
print('packets lost :', str(result.packets_lost))

if result.success(option=3):
    print('success')
    print(result.rtt_avg_ms / 10 / 100) # print average time in seconds

else:
    print('failed')
Related