Limit模块的功能是限制单位时间内进入数据包的数量。
iptables -t filter -R INPUT 1 -p icmp -m limit --limit 10/minute --limit-burst 5 -j ACCEPT
--limit 10/minute
表示一分钟产生10个令牌即6秒一个,--limit-burst 5
表示令牌桶最多可以放5个令牌,此项默认值就是5。Ping本机的响应信息如下:
64 bytes from 192.168.80.133: icmp_seq=0 ttl=64 time=21.3 ms 64 bytes from 192.168.80.133: icmp_seq=1 ttl=64 time=0.564 ms 64 bytes from 192.168.80.133: icmp_seq=2 ttl=64 time=0.559 ms 64 bytes from 192.168.80.133: icmp_seq=3 ttl=64 time=0.478 ms 64 bytes from 192.168.80.133: icmp_seq=4 ttl=64 time=0.488 ms From 192.168.80.133 icmp_seq=5 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=6 ttl=64 time=0.096 ms From 192.168.80.133 icmp_seq=7 Destination Port Unreachable From 192.168.80.133 icmp_seq=8 Destination Port Unreachable From 192.168.80.133 icmp_seq=9 Destination Port Unreachable From 192.168.80.133 icmp_seq=10 Destination Port Unreachable From 192.168.80.133 icmp_seq=11 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=12 ttl=64 time=0.710 ms From 192.168.80.133 icmp_seq=13 Destination Port Unreachable From 192.168.80.133 icmp_seq=14 Destination Port Unreachable From 192.168.80.133 icmp_seq=15 Destination Port Unreachable From 192.168.80.133 icmp_seq=16 Destination Port Unreachable From 192.168.80.133 icmp_seq=17 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=18 ttl=64 time=1.22 ms
因为--limit-burst
是5,所以前5个包顺利拿到令牌进入本机,第6个ping包到来时令牌桶空了,直接被拒绝。此时6秒时间已到,系统便生成一个令牌并放入桶中,此时第7个请求包到达,拿到令牌后进入本机ping成功了。第8,9,10,11,12个ping包请求时,令牌桶空,这5个包直接被拒绝。当到达6秒时又产生一个令牌,这时正好第13个ping包请求,便成功了。以后便如此反复。
把ping的间隔调到2秒,ping -i 2 192.168.80.133
64 bytes from 192.168.80.133: icmp_seq=0 ttl=64 time=51.5 ms 64 bytes from 192.168.80.133: icmp_seq=1 ttl=64 time=0.852 ms 64 bytes from 192.168.80.133: icmp_seq=2 ttl=64 time=0.630 ms 64 bytes from 192.168.80.133: icmp_seq=3 ttl=64 time=0.383 ms 64 bytes from 192.168.80.133: icmp_seq=4 ttl=64 time=0.612 ms 64 bytes from 192.168.80.133: icmp_seq=5 ttl=64 time=0.497 ms From 192.168.80.133 icmp_seq=6 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=7 ttl=64 time=1.35 ms From 192.168.80.133 icmp_seq=8 Destination Port Unreachable From 192.168.80.133 icmp_seq=9 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=10 ttl=64 time=0.110 ms From 192.168.80.133 icmp_seq=11 Destination Port Unreachable From 192.168.80.133 icmp_seq=12 Destination Port Unreachable 64 bytes from 192.168.80.133: icmp_seq=13 ttl=64 time=0.567 ms
刚开始令牌桶中有5个令牌,所以前5个包可以顺利ping通,于此同时系统时间过了10秒,期间系统产生了第1个令牌,第6个包也可以ping通。第7个ping包到达时还没产生第2个令牌,icmp_seq=6包被拒绝。以后便如此反复。
把ping的间隔调到3秒,4秒,5秒等,又会如何?
把--limit 10/minute
的值调大或调小,又会出现什么情况,只有不断尝试不断探索才能不断进步。