Sometimes it’s not enough to estimate the packet loss ratio only, but to make sure that a TCP-connections are stable. Run the “server” instance (sockping -m server -p 65513
) on some host and run the “client” (sockping -m client -h 13.13.13.13 -p 65513
) on another one, and the “client” will connect to the “server” and then it’ll be sending probe messages and expecting replies. If the TCP-session is broken, the “server” states it to STDERR.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
#!/bin/bash function log { echo $(date) ' >> ' $* >&2 } function die { echo $* >&2 exit 1 } while getopts ":m:h:p:" OPT; do case "${OPT}" in m) MODE="${OPTARG}" ;; h) HOST="${OPTARG}" ;; p) PORT="${OPTARG}" ;; \?) die "Invalid option: -${OPTARG}" ;; :) die "Option -${OPTARG} requires an argument." ;; esac done case "${MODE}" in client) [[ -z "${HOST}" ]] && die "Host isn't defined" [[ -z "${PORT}" ]] && die "Port isn't defined" socat TCP:${HOST}:${PORT} EXEC:"${0} -m client-ping",su-d=nobody ;; client-ping) PING=1 while :; do # Sending ping echo -e "$(date +%s)\t${PING}" # Receiving pong read STRING # Checking latency TIME_NEW="$(date +%s)" if [[ ! -z "${TIME_OLD}" ]]; then LATENCY=$(( ${TIME_NEW} - ${TIME_OLD} )) if [[ "${LATENCY}" -gt 2 ]]; then log "The latency is too high (${TIME_NEW} - ${TIME_OLD} = ${LATENCY})" fi fi TIME_OLD="${TIME_NEW}" # Checking sequence delta PONG="$(echo "${STRING}" | cut -f 2)" [[ -z ${PONG} ]] && die "Invalid reply: ${STRING}" STEP=$(( ${PONG} - ${PING} )) [[ "${STEP}" -ne 1 ]] && log "Unexpected sequence step (${PING} - ${PONG} = ${STEP})" PING=$(( ${PONG} + 1 )) # Sleeping sleep 1 done ;; server) [[ -z "${PORT}" ]] && die "Port isn't defined" while : ; do socat TCP-LISTEN:${PORT},fork,su=nobody EXEC:"${0} -m server-ping" sleep 1 log "Restarting" done ;; server-ping) log "${SOCAT_PEERADDR} connected" while :; do read STRING PING="$(echo "${STRING}" | cut -f 2)" [[ -z ${PING} ]] && die "Invalid request: ${STRING}" PONG=$(( ${PING} + 1 )) echo -e "$(date +%s)\t${PONG}" # [[ $(( ${PONG} % 10000 )) -eq 0 ]] && log "Sent the ${PONG}'th pong!" done ;; *) die "Invalid mode: ${MODE}" ;; esac |
Saved to Gist.