温馨提示×

centos iptables怎样限速

小樊
43
2026-10-23 06:23:38
栏目: 智能运维

在 CentOS(使用 iptables) 中,限速通常是通过 iptables 的 limit / hashlimit 模块 或结合 tc(流量控制) 来实现的。下面按常见场景给你示例。


一、使用 iptables limit 模块(简单限速)

1️⃣ 限制 每秒新连接数(防 CC / 扫描)

iptables -A INPUT -p tcp --dport 80 -m limit --limit 10/minute --limit-burst 5 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j DROP

说明:

  • --limit 10/minute:每分钟最多 10 个新包
  • --limit-burst 5:突发允许 5 个
  • 超出直接 DROP

⚠️ 注意:
limit 不是精确带宽限速,而是“包速率限制”。


二、使用 hashlimit(按 IP 限速,更实用)

2️⃣ 限制每个 IP 对 80 端口的访问速率

iptables -A INPUT -p tcp --dport 80 -m hashlimit \
  --hashlimit-name http_limit \
  --hashlimit-mode srcip \
  --hashlimit-upto 10/minute \
  --hashlimit-burst 5 \
  -j ACCEPT

iptables -A INPUT -p tcp --dport 80 -j DROP

参数说明:

  • srcip:按源 IP 限速
  • 10/minute:每个 IP 每分钟最多 10 次
  • 可改成 10/second

三、真正“带宽限速”(推荐用 tc)

iptables 不适合做带宽限速,正确方式是 tc + iptables 打标记

3️⃣ 限制某 IP 上传/下载带宽(示例:限速 1Mbps)

(1)打标记

iptables -t mangle -A POSTROUTING -d 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 1mbit ceil 1mbit
tc filter add dev eth0 protocol ip parent 1:0 prio 1 handle 10 fw flowid 1:10

说明:

  • rate 1mbit:限速 1 Mbps
  • 可改为 512kbit

四、CentOS 7 特别说明

CentOS 7 默认使用 firewalld,需先关闭:

systemctl stop firewalld
systemctl disable firewalld

并确保 iptables 服务存在:

yum install -y iptables-services
systemctl enable iptables
systemctl start iptables

五、常见使用建议

需求 推荐方式
防 CC / 暴力访问 iptables + hashlimit
限制包速率 iptables limit
真正带宽限速 tc
Docker / 容器 用 docker 自带限速

如果你能告诉我:

  • CentOS 版本(6 / 7 / 8)
  • 是 入站 / 出站
  • 限速对象(IP / 端口 / 全局)

我可以给你 可直接用的完整规则。

0 踩