Skip to content

Instantly share code, notes, and snippets.

@330k
Created April 12, 2019 11:39
Show Gist options
  • Save 330k/2e9f22721e1577c25a1d2cc122cc0aa8 to your computer and use it in GitHub Desktop.
Save 330k/2e9f22721e1577c25a1d2cc122cc0aa8 to your computer and use it in GitHub Desktop.
Get hop count the host (without traceroute)
#!/bin/bash
DEST=${1:-8.8.8.8}
MAXHOP=${2:-31}
IPV="-4"
# Ctrl + Cで中断
trap 'echo Breaked; exit 2' 2
# そもそも届かなければ終了
if ! ping -c 1 "${IPV}" "${DEST}" > /dev/null; then
echo "Cannot connect to ${DEST}"
exit 1
fi
# 2分探索
MAX=`expr ${MAXHOP} + 1`
MIN=1
while [ $MIN -lt $MAX ]
do
i=`expr '(' $MIN + $MAX ')' / 2`
echo -ne "(current, min, max) = ($i , $MIN , $MAX)\t" >&2
if ping -c 1 -t $i "${IPV}" "${DEST}" > /dev/null; then
echo "Reached" >&2
MAX=$i
else
echo "Didn't reach" >&2
MIN=`expr $i + 1`
fi
done
if [ "$MAX" -gt "${MAXHOP}" ]; then
echo "Hop count exceed ${MAXHOP}"
exit 1
fi
echo $MAX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment