Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

iptables 實現 NAT 功能完整指南:SNAT、DNAT、Masquerade 與 Port Redirection

編輯:關於伺服器

NAT 核心概念

  • SNAT (Source NAT):修改來源 IP,用於內網主機經公網 IP 上網。
  • DNAT (Destination NAT):修改目的 IP,用於將公網請求轉發至內網伺服器 (端口映射)。
  • Masquerade:SNAT 特殊形式,適用於動態公網 IP (PPPoE 撥號)。
  • Redirect:DNAT 特殊形式,將流量重導向本機其他埠 (透明代理)。

netfilter NAT 表與鏈

鏈處理時機典型用途
PREROUTING路由決定前DNAT、Redirect
POSTROUTING路由決定後SNAT、Masquerade
OUTPUT本機產生封包本機發出的 DNAT

所有 NAT 規則必須加 -t nat 指定表。

常用語法速查

# 新增規則到鏈尾
iptables -t nat -A POSTROUTING ...

# 插入到鏈首 (優先匹配)
iptables -t nat -I PREROUTING ...

# 指定來源/目的
-s 192.168.1.0/24   -d 202.110.123.100

# 指定介面 (PREROUTING 用 -i, POSTROUTING 用 -o)
-i eth1   -o eth0

# 指定協議與埠
-p tcp --dport 80

# 動作
-j SNAT --to-source 1.2.3.4
-j DNAT --to-destination 192.168.1.100
-j MASQUERADE
-j REDIRECT --to-port 3128

實戰案例

案例一:撥號上網共享 (Masquerade)

modprobe ip_tables
modprobe ip_nat_ftp
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE

案例二:IP 映射 (公網 IP 對應內網 Web 伺服器)

假設:

  • 防火牆外網介面 eth0: 202.110.123.1,內網 eth1: 192.168.1.1
  • 單位 A 內網 Web: 192.168.1.100,映射公網: 202.110.123.100
  • 單位 B 內網 Web: 192.168.1.200,映射公網: 202.110.123.200
# 綁定公網 IP 到外網介面
ifconfig eth0 add 202.110.123.100 netmask 255.255.255.0
ifconfig eth0 add 202.110.123.200 netmask 255.255.255.0

# DNAT: 公網進來 → 內網伺服器
iptables -t nat -A PREROUTING -i eth0 -d 202.110.123.100 -j DNAT --to 192.168.1.100
iptables -t nat -A PREROUTING -i eth0 -d 202.110.123.200 -j DNAT --to 192.168.1.200

# SNAT: 內網回應 → 偽裝成公網 IP
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.100 -j SNAT --to 202.110.123.100
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.200 -j SNAT --to 202.110.123.200

案例三:透明代理 (Squid + Redirect)

iptables -t nat -A PREROUTING -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j REDIRECT --to-port 3128

前置準備

  1. 核心編譯支援:CONFIG_IP_NF_NAT, CONFIG_IP_NF_TARGET_MASQUERADE, CONFIG_IP_NF_TARGET_REDIRECT。
  2. 載入模組:modprobe ip_tables; modprobe ip_nat_ftp (iptable_nat 會自動載入)。
Copyright © Windows教程網 All Rights Reserved