Skip to content

Instantly share code, notes, and snippets.

@cjhanks
Created December 28, 2015 16:51
Show Gist options
  • Save cjhanks/721bd23e12e91d21843a to your computer and use it in GitHub Desktop.
Save cjhanks/721bd23e12e91d21843a to your computer and use it in GitHub Desktop.
TC Rate limiting
#!/bin/bash
# vim: ts=2 sw=2 et ai tw=80
################################################################################
# Script designed to shape system bandwidth usage based on the very fine
# reference found https://www.iplocation.net/traffic-control
################################################################################
set -e
# -- CONSTANTS
TC=/sbin/tc
IF=em1
LIMIT_I=95mbit # download rate
LIMIT_O=95mbit # upload rate
# Filter options for limiting the intended interface.
U32="$TC filter add dev $IF protocol ip parent 1:0 prio 1 u32"
# WARNING: If the device order ever changes, this could cause problems
ME=$(hostname -I | cut -f1 -d ' ')
# -- METHODS
checkDeviceValid() {
local block="(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
local regex="${block}\.${block}\.${block}\.${block}"
local count=$(ip addr show ${IF} |
grep ${ME} 2> /dev/null |
grep -c -E -o ${regex})
if [ ${count} -eq 0 ]
then
return 1
else
return 0
fi
}
start() {
echo "Starting"
${TC} qdisc add dev ${IF} root handle 1: htb default 30
${TC} class add dev ${IF} parent 1: classid 1:1 htb rate ${LIMIT_I}
${TC} class add dev ${IF} parent 1: classid 1:2 htb rate ${LIMIT_O}
${U32} match ip dst ${ME}/32 flowid 1:1
${U32} match ip src ${ME}/32 flowid 1:2
}
stop() {
echo "Stopping"
${TC} qdisc del dev ${IF} root
}
printUsage() {
echo "Usage: $0 {start|stop}"
exit 1
}
# -- MAIN
action=$1
if [ -z ${action} ]
then
printUsage
fi
if ! checkDeviceValid
then
echo "Invalid network device: ${IF}"
exit 1
fi
echo "Configuring ${IF} with IP ${ME}"
case ${action} in
start)
start
;;
stop)
stop
;;
*)
printUsage
;;
esac
echo "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment