How to use OS X's terminal to ping an IP using the latency as a stopping condition for a loop?

1

What I'd like to do is to ping an IP while the latency is above an specific value. I think an example will help:

Let's suppose I have the following result to the "ping *IP here*" command:

PING *IP here* (*IP here*): 56 data bytes
64 bytes from *IP here*: icmp_seq=0 ttl=53 time=127.238 ms
64 bytes from *IP here*: icmp_seq=1 ttl=53 time=312.762 ms
64 bytes from *IP here*: icmp_seq=2 ttl=53 time=251.475 ms
64 bytes from *IP here*: icmp_seq=3 ttl=53 time=21.174 ms
64 bytes from *IP here*: icmp_seq=4 ttl=53 time=27.953 ms

I'd like a way to make the ping stop after the latency drops below a given value. Let's say 100, so in the example above it'd stop after the 4th result.

Rafael Duarte

Posted 2014-10-22T01:03:11.790

Reputation: 11

Rafael, if the answer below solved your problem, could you please Accept it? – jimtut – 2014-10-30T17:05:16.287

Answers

2

This script seems to work:

#!/bin/sh

HOST="verizon.net"
MIN_TIME=80

LOOP="TRUE"    
while [ $LOOP = "TRUE" ]
do
  latency=`ping -c 1 $HOST | head -2 | tail -1 | sed -e 's/.*time=\(.*\) ms/\1/' | sed -e 's/\..*//'`
  echo "Latency: $latency"
  if [ $latency -lt $MIN_TIME ]
  then
    echo "Target latency ($MIN_TIME) achieved!"
    LOOP="FALSE"    
  fi
done

Output looks like this, stopping when it gets below my threshold (80 ms):

Latency: 83
Latency: 88
Latency: 119
Latency: 77
Target latency (80) achieved!

Adjust the variables in the script for your use. You might need to tweak the head/tail/sed pieces for your ping output. This was written using Mac OS X 10.9's ping.

jimtut

Posted 2014-10-22T01:03:11.790

Reputation: 832