Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
tcp_throttle uses packet shaping to add delay to specific packets
#!/bin/bash
# this uses packet shaping to add delay to specific packets.
# for more informatino about "netem" the network emulation module
# see http://www.linuxfoundation.org/collaborate/workgroups/networking/netem
# or http://lartc.org/howto/index.html section 9 and 12
# please add more options to this script as needed.
function usage() {
echo "USAGE: $(basename $0) --interface=<ethX> (--dport=<PORT> | --host=<IP>) --delay=<DELAY_SPEC> --start"
echo " $(basename $0) --interface=<ethX> (--stop | --status)"
echo " DELAY_SPEC examples: '100ms 10ms', '3000ms 2000ms distribution normal'"
exit 1
}
port=""
delay="100ms"
dev="lo"
host=""
while [ "$1" != "" ]; do
param=${1%%=*}
value=${1#*=}
case $param in
--dport)
port="dport $value 0xffff"
;;
--host)
host="dst $value"
;;
--delay)
delay=$value
;;
--interface)
dev=$value
;;
--start)
START=1
;;
--stop)
STOP=1
;;
--status)
STATUS=1
;;
--help | -h)
usage
;;
*)
echo "ERROR: bad argument '$1'"
usage
;;
esac
shift
done
if [ -n "$host" ] && [ -n "$port" ]; then
echo "ERROR: you can only use --host or --dport, not both"
usage
fi
if [ $(expr ${START:-0} + ${STOP:-0} + ${STATUS:-0}) != 1 ] ; then
echo "ERROR: use exactly one of --start --stop --status"
usage
fi
if [ -n "$STATUS" ]; then
/sbin/tc -s qdisc
/sbin/tc filter show dev $dev
fi
if [ -n "$START" ]; then
echo "delaying $host $port on interface $dev for $delay"
/sbin/tc qdisc del dev $dev root 2>/dev/null
/sbin/tc qdisc add dev $dev root handle 1: prio
/sbin/tc filter add dev $dev protocol ip parent 1: prio 1 u32 match ip $host $port flowid 1:3
/sbin/tc qdisc add dev $dev parent 1:3 handle 31: netem delay $delay
fi
if [ -n "$STOP" ]; then
/sbin/tc qdisc del dev $dev root
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment