Skip to content

Instantly share code, notes, and snippets.

@bidulock
Last active January 8, 2024 16:41
Show Gist options
  • Save bidulock/11233356 to your computer and use it in GitHub Desktop.
Save bidulock/11233356 to your computer and use it in GitHub Desktop.
Slow down traffic on localhost through a single port
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "You must run this as root."
exit 1
fi
I=lo
PORT=${PORT-23000}
DELAY=${DELAY-25ms}
DELAY_RAND=${DELAY_RAND-5ms}
RATE=${RATE-1Mbps}
tc qdisc del dev $I root > /dev/null 2>&1
if [[ $1 == 'disable' ]]; then
echo "Traffic control has been disabled"
exit 0
fi
tc qdisc add dev $I handle 1: root htb
tc class add dev $I parent 1: classid 1:1 htb rate $RATE
tc qdisc add dev $I parent 1:1 handle 10: netem delay $DELAY $DELAY_RAND 25%
tc filter add dev $I protocol ip parent 1: prio 1 u32 match ip dport $PORT 0xffff flowid 1:1
tc filter add dev $I protocol ip parent 1: prio 1 u32 match ip sport $PORT 0xffff flowid 1:1
r='\e[0;31m'
n='\e[0m'
echo -e "Traffic control set on localhost port $r$PORT$n with a rate of $r$RATE$n and delay of $r$DELAY +-$DELAY_RAND$n"
echo -e "\nTo change values use the env variables PORT, RATE and DELAY"
echo "E.g., sudo RATE=500Kbps DELAY=100ms DELAY_RAND=25ms PORT=3000 $0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment