限制程式頻寬(bandwidth/traffic shaping) - Linux

Table of Contents

昨天搞了三個多小時,才從網路&manpage拼湊出來的
網路上的例子都動輒十幾二十條rule,想要簡單反而都弄不起來XD

我要的很簡單,只是和win netlimiter一樣限制一個程式的流量
因為skype跟本看到多少流量就把它全部用光Orz

# tc part:
tc qdisc add dev eth0 root handle 1: htb # major=1
# Major 是綁qdisc的, 任何還沒用到的 0 < major < ffff 都可.
# 0 被 "super root" - pfifo_fast 用掉了
# 所有iface上的封包都會先被丟到root qdisc, 再被決定下一部步丟進哪個class.

tc class add dev eth0 parent 1: classid 1:10 htb rate 128kbit # minor=10
# Class 下才能開始限流. parent 可以是 qdisc 或另一個 class.
# Major 一定要跟parrent, minor 在同一個major下不重複就好.

tc filter add dev eth0 parent 1: handle 115 fw classid 1:10 # mark=115
# 如果沒有rule, 流量就不會進到class裡, qdisc/class有點像iptables的一個chain.
# 哪些封包會從 1: 進到 1:10 裡?和ipt不同的在: class必需是跟著單一的qdisc.
# 可以說不同的 qdisc 就像是不同的 table?
# 不過 tc 可以在一個 class 下設一個新table, 現在先不理它
# 我用 iptables 的 mark 來分類,此 handle 和一開始的 "root handle 1:" 完全無關

# iptables
iptables -N skype-o
iptables -A OUTPUT -m owner --gid-owner nlimit -j skype-o
# addgroup nlimit, chgrp nlimit, 用sgid吧skype標出來
iptables -A skype-o -j CONNMARK --set-mark 0x73 # for conntrack
iptables -A skype-o -j MARK --set-mark 0x73 # for tc
iptables -A skype-o -j ACCEPT # end chain

iptables -N skype-ui
-A INPUT -p udp -m connmark --mark 0x73 -j skype-ui
# 用connmark: 可以直接抓到skype的udp incomming,不會和bt dht/traker之類混到
-A skype-ui -m limit --limit 90/sec -j ACCEPT
# 這樣大概是100kbit/s, drop掉超過的,對方就會慢慢減速
-A skype-ui -j DROP


------------------------

最後是如果你要刪filter... 比建立還難XD,因為我設的時候沒指定prio
$ tc filter show dev eth0
filter parent 1: protocol all pref 49152 fw
filter parent 1: protocol all pref 49152 fw handle 0x73 classid 1:10
所以要下的是: tc filter del dev eth0 protocol all pref 49152 fw
class,qdisc只要把add改成del就OK了
如果 tc qdisc del dev eth0 root 會直接清空所有的東西

--

All Comments

Dora avatarDora2013-06-03
看來重點是 iptables uid/gid match ,蠻實用的
Vanessa avatarVanessa2013-06-08
我還不知道原來 iptables 有這種東西,推一個
Hedda avatarHedda2013-06-10
我覺得是tc比較難搞... iptables有很多簡短的例子可找
Brianna avatarBrianna2013-06-13
wondershaper trickle
Steve avatarSteve2013-06-15
你可以把程式上色好閱讀一點