How to limit ingress bandwith with tc command in Linux

tc (Traffic Control) is a builtin command in linux, can be used to configure traffic control rules in linux kernel.

tc_setup.sh is a bash script that I use to simulate a low-speed network during software testing. it sets ingress bandwith limit with the tc command.

#!/bin/sh
# Modify speed variable according to your needs
SPEED=30kbps
# Find the default network device in route table
DEVICE=$(route | grep '^default' | grep -o '[^ ]*$')

# Linux does not support shaping on ingress
# but we can redirect ingress taffic to ifb device, then do
# taffic shaping on egress queue of ifb device.

if test -z "$(lsmod | grep ifb)"; then
    modprobe ifb
fi

if test -z "$(ip link | grep ifb0)"; then
    ip link add name ifb0 type ifb
    ip link set dev ifb0 up
fi

tc qdisc add dev ifb0 root handle 1: htb r2q 1
tc class add dev ifb0 parent 1: classid 1:1 htb rate $SPEED
tc filter add dev ifb0 parent 1: matchall flowid 1:1

tc qdisc add dev $DEVICE ingress
tc filter add dev $DEVICE ingress matchall action mirred egress redirect dev ifb0

tc_clean.sh is used to clean bandwith limit rules

#!/bin/sh
DEVICE=$(route | grep '^default' | grep -o '[^ ]*$')
tc qdisc del dev $DEVICE ingress
tc qdisc del dev ifb0 root

Test results on CentOS 7.8

# wget http://speedtest.fremont.linode.com/100MB-fremont.bin
--2021-09-24 10:44:43--  http://speedtest.fremont.linode.com/100MB-fremont.bin
Resolving speedtest.fremont.linode.com (speedtest.fremont.linode.com)... 2600:3c01::f03c:91ff:feae:68d, 50.116.14.9
Connecting to speedtest.fremont.linode.com (speedtest.fremont.linode.com)|2600:3c01::f03c:91ff:feae:68d|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104857600 (100M) [application/octet-stream]
Saving to: ‘100MB-fremont.bin’

30% [=========================>                                                               ] 31,633,828  15.0MB/s             ^C
#./tc_setup.sh
# wget http://speedtest.fremont.linode.com/100MB-fremont.bin
--2021-09-24 10:45:12--  http://speedtest.fremont.linode.com/100MB-fremont.bin
Resolving speedtest.fremont.linode.com (speedtest.fremont.linode.com)... 2600:3c01::f03c:91ff:feae:68d, 50.116.14.9
Connecting to speedtest.fremont.linode.com (speedtest.fremont.linode.com)|2600:3c01::f03c:91ff:feae:68d|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104857600 (100M) [application/octet-stream]
Saving to: ‘100MB-fremont.bin’

 0% [                                                                                         ] 171,104     27.4KB/s  eta 60m 25s^C


Leave a Reply

Your email address will not be published. Required fields are marked *