在 CentOS 下使用 iptables 进行限速,本质是借助 iptables + 内核的流量控制(tc / 哈希限制) 来实现。
下面按常见需求给你几种可用的做法,从简单到专业。
适合:防止单个 IP 疯狂请求
iptables -A INPUT -p tcp --dport 80 -m connlimit \
--connlimit-above 20 -j REJECT
✅ 不能限制“速率”,只能限制“连接数”
hashlimit 限速(推荐 ✅)适合:限制每秒/每分钟包数或流量
iptables -A INPUT -p tcp --dport 80 \
-m hashlimit \
--hashlimit 10/sec \
--hashlimit-mode srcip \
--hashlimit-name http_limit \
-j ACCEPT
iptables -A INPUT -p tcp --dport 80 \
-m hashlimit \
--hashlimit 10/sec \
--hashlimit-burst 20 \
--hashlimit-mode srcip \
--hashlimit-name http_limit \
-j ACCEPT
iptables -A INPUT -p tcp --dport 80 \
-m hashlimit \
--hashlimit 1mb/sec \
--hashlimit-mode srcip \
--hashlimit-name speed_limit \
-j ACCEPT
| 单位 | 含义 |
|---|---|
pkt/sec |
包/秒 |
pkt/min |
包/分钟 |
kb/sec |
KB/秒 |
mb/sec |
MB/秒 |
适合:限制出口总带宽
tc qdisc add dev eth0 root tbf rate 10mbit burst 32kbit latency 400ms
查看:
tc qdisc show dev eth0
删除:
tc qdisc del dev eth0 root
⚠️ iptables 本身不能直接限速下载
推荐方案:
| 场景 | 方案 |
|---|---|
| 限制下载 | tc |
| 限制上传 | iptables + hashlimit |
| 限制单 IP | hashlimit |
| 限制总带宽 | tc |
iptables -A INPUT -p tcp --dport 80 \
-m hashlimit \
--hashlimit 20/sec \
--hashlimit-burst 50 \
--hashlimit-mode srcip \
--hashlimit-name http \
-j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j DROP
CentOS 7 默认用 firewalld
systemctl stop firewalld
systemctl disable firewalld
yum install iptables-services -y
systemctl enable iptables
规则重启会丢失
service iptables save
不建议限制 ICMP(ping),否则影响网络诊断
你可以直接告诉我:
我可以给你一份可直接复制执行的完整脚本 ✅