Posts Tagged ‘fping’

Measuring ping latency of a server

December 27, 2012 Leave a comment

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.