Home > python > Measuring ping latency of a server

Measuring ping latency of a server

You have a list of servers (e.g. proxies) and you want to choose the fastest one. How to measure the ping latencies?

There is a nice Unix command for this called “fping” (sudo apt-get install fping). “Unlike ping, fping is meant to be used in scripts, so its output is designed to be easy to parse.


$ fping -C 3 -q : 389.08 411.15 411.82

It sends 3 packets and after the colon it prints each response time. If a response time could not be measured then you will see a “-” in its place.

In Python, here is my solution:

import shlex  
from subprocess import Popen, PIPE, STDOUT

def get_simple_cmd_output(cmd, stderr=STDOUT):
    Execute a simple external command and get its output.
    args = shlex.split(cmd)
    return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0]

def get_ping_time(host):
    host = host.split(':')[0]
    cmd = "fping {host} -C 3 -q".format(host=host)
    res = [float(x) for x in process.get_simple_cmd_output(cmd).strip().split(':')[-1].split() if x != '-']
    if len(res) > 0:
        return sum(res) / len(res)
        return 999999

It calculates the average of the response times. If no response time could be measured then it returns a big value.

I sent this solution to SO too.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: