Get Ping Latency from Host

Get ping latency from host

You can easily extend simple ping to calculate the latency. Simpleping.h defines the SimplePingDelegate protocol. There are two methods of interest - didSendPacket and didReceivePingResponsePacket. A naive implementation for timing the latency would be

@property (strong,nonatomic) NSDate *start;

- (void)simplePing:(SimplePing *)pinger didSendPacket:(NSData *)packet
{
self.start=[NSDate date];
}

- (void)simplePing:(SimplePing *)pinger didReceivePingResponsePacket:(NSData *)packet
{
NSDate *end=[NSDate date];
double latency = [end timeIntervalSinceDate:self.start]*1000.0;

//TODO - Do something with latency
}

I say this is a niave implementation because it doesn't deal with the case where another packet is sent before the response is received or where packets are dropped. To deal with this you would need to examine the packet data to determine whether the sequence number was consistent between the send and receive events.

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

Get ping time in python

A ping is not the same thing as a HTTP connection! The first is a low level ICMP packet that is used to test connectiviy and find round-trip time mainly on a local network. It is generaly not used on broad internet, because for security reasons it is often blocked by firewall and external routers.

If you want to know the time necessary to establish the connexion to a server, do what you would in real world: look at your watch, do the job, look again at your watch to see elapsed time. In Python it gives

#import time
...
def connect_time():
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(REMOTE_SERVER)
# connect to the host -- tells us if the host is actually
# reachable
before = time.clock() # from Python 3.3 and above use before = time.perf_counter()
s = socket.create_connection((host, 80), 2)
after = time.clock() # from Python 3.3 and above use after = time.perf_counter()
return after - before
except:
return -1


Related Topics



Leave a reply



Submit