Measuring ping latency of a server - Python
If you are already comfortable with parsing strings, you can use the subprocess module to get the data you are looking for into a string, like this:
>>> import subprocess
>>> p = subprocess.Popen(["ping.exe","www.google.com"], stdout = subprocess.PIPE)
>>> print p.communicate()[0]
Pinging www.l.google.com [209.85.225.99] with 32 bytes of data:
Reply from 209.85.225.99: bytes=32 time=59ms TTL=52
Reply from 209.85.225.99: bytes=32 time=64ms TTL=52
Reply from 209.85.225.99: bytes=32 time=104ms TTL=52
Reply from 209.85.225.99: bytes=32 time=64ms TTL=52
Ping statistics for 209.85.225.99:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 59ms, Maximum = 104ms, Average = 72ms
Following hlovdal's suggestion to work with fping, here is my solution that I use for testing proxies. I only tried it under Linux. If no ping time could be measured, a big value is returned. Usage: print get_ping_time('<ip>:<port>')
.
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 get_simple_cmd_output(cmd).strip().split(':')[-1].split() if x != '-']
if len(res) > 0:
return sum(res) / len(res)
else:
return 999999
If you want to avoid implementing all the network communication details you could probably try to build something on top of fping:
fping is a like program which uses the Internet Control Message Protocol (ICMP) echo request to determine if a target host is responding. fping differs from ping in that you can specify any number of targets on the command line, or specify a file containing the lists of targets to ping. Instead of sending to one target until it times out or replies, fping will send out a ping packet and move on to the next target in a round-robin fashion.