温馨提示×

centos iptables能否限速

小樊
32
2026-09-17 21:03:09
栏目: 智能运维

可以的,CentOS 下的 iptables 本身可以做限速(流量控制/限流),但能力有限,通常结合 iptables + tc(traffic control) 使用效果更好。下面分情况说明。


一、iptables 自身能做的限速(基于“报文数量/连接”)

iptables 可以通过 limit / hashlimit 模块实现限速或限连接

1. 使用 limit 模块(限制包速率)

适合防止洪水攻击、限制请求频率。

# 每秒最多 10 个包,突发 20 个
iptables -A INPUT -p tcp --dport 80 -m limit --limit 10/s --limit-burst 20 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j DROP

⚠️ 注意:

  • 这是按包限速,不是按带宽(MB/s)
  • 对大包小包效果不一致

2. 使用 hashlimit(按 IP 限速)

更适合“每个 IP 限速”。

# 每个 IP 每秒最多 20 个包
iptables -A INPUT -p tcp --dport 22 -m hashlimit \
  --hashlimit-mode srcip \
  --hashlimit-above 20/sec \
  --hashlimit-name ssh_limit \
  -j DROP

也可以限制连接数:

# 每个 IP 最多 5 个 SSH 连接
iptables -A INPUT -p tcp --dport 22 -m connlimit --connlimit-above 5 -j DROP

二、iptables + tc(真正的带宽限速)

如果你要的是 “限制某个 IP / 端口的带宽(如 1Mbps)”,iptables alone 不够,要用 tc(Traffic Control)

示例:限制 eth0 出口带宽为 1Mbps

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

示例:限制某个 IP 的上行带宽

tc qdisc add dev eth0 root handle 1: htb
tc class add dev eth0 parent 1: classid 1:1 htb rate 1mbit
tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip src 192.168.1.100 flowid 1:1

三、CentOS 版本注意事项

CentOS 6 / 7

  • 默认使用 iptables
  • 模块齐全(limithashlimitconnlimit

CentOS 8+

  • 默认是 nftables
  • iptables 是兼容层
  • 建议直接用 nftables + tc

四、总结

需求 推荐方案
限制请求频率 iptables limit / hashlimit
限制连接数 connlimit
限制带宽(MB/s) iptables + tc
精细 QoS tc(HTB / HFSC)

如果你能告诉我:

  • CentOS 版本
  • 要限制 入站还是出站
  • 是按 IP、端口还是整体带宽

我可以直接给你一份可复制的配置文件

0