Skip to content

Instantly share code, notes, and snippets.

@ploxiln
Created April 30, 2015 16:04
Show Gist options
  • Save ploxiln/d76a150c719c778eb8c4 to your computer and use it in GitHub Desktop.
Save ploxiln/d76a150c719c778eb8c4 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This uses linux "transport control" aka tc to affect OUTGOING packets.
# For more information about "netem", the network emulation module, see:
# http://www.linuxfoundation.org/collaborate/workgroups/networking/netem
# http://lartc.org/howto/index.html section 9 and 12.
usage() {
echo "USAGE: $(basename $0) --interface=<ethX> (--dport=<PORT> | --host=<IP>) (--delay=<DELAY_SPEC> | --loss=<LOSS_SPEC>) --start"
echo " $(basename $0) --interface=<ethX> (--stop | --status)"
echo " DELAY_SPEC examples: '1000ms', '100ms 10ms', '3000ms 2000ms distribution normal'"
echo " LOSS_SPEC examples: '2%'"
exit 1
}
port=""
delay=""
loss=""
dev="lo"
host=""
while [ $# -gt 0 ]; do
param=${1%%=*}
value=${1#*=}
case $param in
--dport)
port="dport $value 0xffff"
;;
--host)
host="dst $value"
;;
--delay)
delay=$value
;;
--loss)
loss="random $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 "affecting outgoing to $host $port on interface $dev - delay='$delay' loss='$loss'"
/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 $delay} ${loss:+loss $loss}
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