
我有一個開放的端口,40002,我想限制該端口同一時間只能由一個IP地址(不是特定地址)連接。如果已經有一個IP位址連接到該端口,則其他IP位址將無法連接。
可以透過 Iptables 或腳本進行設定嗎?我的系統是 Ubuntu 14.04 謝謝。
答案1
您可以透過設定 iptables 來做到這一點。
/sbin/iptables -A INPUT -p tcp --syn --dport $port -m connlimit --connlimit-above N -j REJECT --reject-with tcp-reset
# save the changes see iptables-save man page, the following is redhat and friends specific command
service iptables save
範例:限制每個 IP/主機的 SSH 連接
/sbin/iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
# save the changes see iptables-save man page, the following is redhat and friends specific command
service iptables save
測試:
#!/bin/bash
ip="202.1.2.3"
port="80"
for i in {1..100}
do
# do nothing just connect and exit
echo "exit" | nc ${ip} ${port};
done
好的:要限制最大連線數,這裡是使用 ip limit 模組的範例:
iptables -A INPUT -p tcp --syn -dport 40002 -m iplimit --iplimit-above 3 -J REJECT
如果連接了 3 個 IP,這將拒絕連線。抱歉,如果我誤解了你的問題;)