Ubuntu 中开放 UDP 端口

在 Ubuntu 中开放 UDP 端口,通常涉及以下几步:

🔧 步骤一:确认使用的防火墙

Ubuntu 默认使用 ufw(Uncomplicated Firewall),但也可能用 iptables 或 nftables。以下以 ufw 为例说明。

✅ 用 ufw 开放 UDP 端口(推荐)

1. 开启防火墙(如果还未开启):

sudo ufw enable

2. 开放 UDP 端口(以 5060 为例):

sudo ufw allow 5060/udp

3. 查看已开放的端口规则:

sudo ufw status

你将看到类似这们的内容输出:

4. 开放一个范围的 UDP 端口(例如 10000–20000):

sudo ufw allow 10000:20000/udp

✅ 如果使用 iptables:

sudo iptables -A INPUT -p udp --dport 5060 -j ACCEPT

要开放端口范围:

sudo iptables -A INPUT -p udp --dport 10000:20000 -j ACCEPT

Ubuntu 20.04+ 使用 iptables-persistent:

sudo apt install iptables-persistent sudo netfilter-persistent save

✅ 如果使用 nftables:

sudo nft add rule inet filter input udp dport 5060 accept

🧪 验证端口是否开放

你可以在目标机器上监听 UDP 端口:

sudo nc -ul 5060

然后从另一台机器发送数据测试:

echo "test" | nc -u your-server-ip 5060