使用 Linux TC 进行流量限制

1. Linux 下的流量控制原理

2.1 查看网卡

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
ifconfig

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 1.1.1.1  netmask 255.255.254.0  broadcast 1.1.1.1
        inet6 1::1:1:1:1  prefixlen 64  scopeid 0x20<link>
        ether 1:1:1:1:1:1  txqueuelen 1000  (Ethernet)
        RX packets 2980910  bytes 2662352343 (2.4 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1475969  bytes 122254809 (116.5 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

2.2 配置 qdisc-class-filter

  • 创建 qdisc 根队列
1
tc qdisc add dev eth0 root handle 1: htb default 1
  • 创建第一级 class 绑定所有带宽资源
1
2
3
4
tc class show dev ifb0

class htb 1:10 parent 1:1 prio 0 rate 48Mbit ceil 48Mbit burst 1590b cburst 1590b 
class htb 1:1 root rate 48Mbit ceil 48Mbit burst 1590b cburst 1590b 
  • 查看 filter 配置
1
2
3
4
5
6
tc filter show dev ifb0

filter parent 1: protocol ip pref 16 u32 chain 0 
filter parent 1: protocol ip pref 16 u32 chain 0 fh 800: ht divisor 1 
filter parent 1: protocol ip pref 16 u32 chain 0 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:10 not_in_hw 
  match 01020304/ffffffff at 16
  • 清理全部配置
1
2
3
tc qdisc del dev eth0 ingress
tc qdisc del dev ifb0 root
modprobe -r ifb

4. 参考

  • https://arthurchiao.art/blog/lartc-qdisc-zh/
  • https://serverfault.com/questions/350023/tc-ingress-policing-and-ifb-mirroring