Search code examples
iosobjective-cpingbandwidthlatency

Get ping latency from host


I'm trying to get the latency from host for a pretty good time and I'm stuck in. Already tried Simple Ping , but seems it doesn't return the latency. The closest I've done was when I use the TKC-PingTest for MAC OS. That works perfect but only in the iPhone Simulator because when use the iPhone I get an error due the patch "/sbin/ping" TKC uses. Besides these two, I already tried many others and got nothing.


Solution

  • 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.