温馨提示×

ubuntu iptables怎么限速

小樊
40
2026-09-19 02:21:12
栏目: 智能运维

在 Ubuntu 下使用 iptables 进行限速,通常是结合 tc(traffic control) 或者直接利用 iptables 的 hashlimit / limit 模块来实现。下面按常见场景说明。


一、使用 iptables + hashlimit(最常用,推荐)

1️⃣ 限制某个 IP 的带宽(按包速率)

例如:限制 单个 IP 每秒最多 10 个包

iptables -A INPUT -p tcp --dport 80 \
  -m hashlimit \
  --hashlimit-mode srcip \
  --hashlimit-above 10/sec \
  --hashlimit-name http_limit \
  -j DROP

含义:

  • --hashlimit-mode srcip:按源 IP 统计
  • --hashlimit-above 10/sec:超过 10 包/秒就 DROP
  • 可用于防 CC、限速

2️⃣ 限制单个 IP 带宽(例如 1MB/s)

iptables -A INPUT -p tcp --dport 80 \
  -m hashlimit \
  --hashlimit-mode srcip \
  --hashlimit-above 8mb/min \
  --hashlimit-name http_bw \
  -j DROP

常用单位:

  • kb/min
  • mb/min
  • pkt/sec

二、限制整体流量(limit 模块)

限制 ICMP(防 ping 攻击)

iptables -A INPUT -p icmp --icmp-type echo-request \
  -m limit --limit 1/sec --limit-burst 5 \
  -j ACCEPT

iptables -A INPUT -p icmp -j DROP

limit 是全局限速,不区分 IP


三、真正的“带宽限速”(用 tc,更精确)

iptables 不能直接限制 Mbps,只能限制包速率。
要限制如 100kbps / 1mbps,要用 tc

示例:限制 eth0 出方向为 1Mbps

tc qdisc add dev eth0 root tbf rate 1mbit burst 32kbit latency 400ms

删除:

tc qdisc del dev eth0 root

四、按 IP 限速(tc + iptables 标记)

1️⃣ 标记特定 IP

iptables -t mangle -A POSTROUTING -s 192.168.1.100 -j MARK --set-mark 10

2️⃣ tc 限速

tc qdisc add dev eth0 root handle 1: htb
tc class add dev eth0 parent 1: classid 1:10 htb rate 512kbit
tc filter add dev eth0 protocol ip parent 1: prio 1 handle 10 fw flowid 1:10

五、常用排查命令

iptables -L -n -v
tc qdisc show
tc class show dev eth0

六、建议总结

需求 推荐方式
防刷接口 iptables hashlimit
防 ping iptables limit
精确带宽限速 tc
单 IP 限速 tc + iptables MARK

如果你能说清楚:

  • 限速 入站还是出站
  • 限速 单个 IP 还是整体
  • 目标速率(如 500kbps)

我可以给你一份可直接复制用的完整规则。

0 踩