Friday, August 19, 2011

User wise bandwidth control

Suppose you want to control download speed of a user test to 1mbps. linux provide iptables and tc command to help you in this scenario. HTB alogorithm can be implemented on network interface to control that.


Mark packet originated by user test with mark 6

iptables -t mangle -A OUTPUT -p tcp -m owner --uid-owner test -j MARK --set-mark 6

Following script can help in this situation

TC=/sbin/tc

IF=eth0

DNLD=1mbit

start() {

$TC qdisc add dev $IF root handle 1: htb default 30

$TC class add dev $IF parent 1: classid 1:1 htb rate $DNLD

$TC filter add dev $IF protocol ip parent 1:0 prio 1 handle 6 fw flowid 1:1

}

stop() {

$TC qdisc del dev $IF root

}

restart() {

stop

sleep 1

start

}

show() {

$TC -s qdisc ls dev $IF

}

case "$1" in

start)

echo -n "Starting bandwidth shaping: "

start

echo "done"

;;

stop)

echo -n "Stopping bandwidth shaping: "

stop

echo "done"

;;

restart)

echo -n "Restarting bandwidth shaping: "

restart

echo "done"

;;

show)

echo "Bandwidth shaping status for $IF:"

show

echo ""

;;

*)

pwd=$(pwd)

echo "Usage: tc.bash {start
stop
restart
show}"

;;

esac

exit 0