Given a list of IPs, how can it be sorted so that the "nearest" or lowest latency is sorted to the top, "farthest" or longest latency, is at the end?


Here's my solution, specific to NIS, written up in bash:

yplist=( $( ypcat ypservers|xargs -n1 host|sed -n '/has.address/s/.*[[:space:]]//p'|sort -u ) )
nearest=( $( for pp in ${yplist[@]}; do ping -q -n -c 5 -i 0.3 $pp|awk -F/ '/^rtt/{printf "%d:",($5*1000)}'; echo $pp; done|sort -n -t: -k1|cut -d: -f2 ) )
printf "ypserver %s\n" ${nearest[@]} >/etc/yp.conf

That's a pipeline that grew in the telling, so here goes:

  • $yplist is an array of hosts, and works as my source list
  • $nearest takes $yplist and pings each in turn
  • the output of ping is narrowed by awk to match only the summary line
  • slight hack: using / as the delimiter, the avg roundtrip in ms is multiplied by 1000 to give an integer value in μs
  • the follow-up echo $pp just sticks the IP in question on the end of the line
  • the entire for loop is sorted numerically on field #1 - shorter response time averages will float to the top
  • the first field is snipped off leaving just the IPs
  • this list of IPs is then assigned into the $nearest array

This is the resulting list of IPs, with the shortest latency at the top.

(The final printf line just writes out a new /etc/yp.conf prefixing each IP by "ypserver" for the NIS config.)

I had a think about adding the minimum latency to a factor of the deviance (mdev in ping output), to expose potentially unreliable hosts. However, this statistic would only be useful if the ping per host ran over several hours or even days; and what would the factor be? It seems like somewhere between 10 and 100 would be about right, but this would have to be tuned for tolerance to unreliability. And that seems an awful lot of work to purify the results by maybe 5%.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.