Search code examples
pythonnetwork-programmingtcplatency

Measuring ping latency of a server - Python


I have a list of server IP addresses, I need to check if each one is online and how long the latency is.

I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.


Any ideas?


Solution

  • 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