NAT是什么?计算机网络中的网络地址转换详解
DevOps

NAT是什么?计算机网络中的网络地址转换详解

NAT(网络地址转换)是一种让多台设备共用一个公网IP地址的技术。深入了解PAT、静态NAT、动态NAT的工作原理,以及NAT在路由器、云端VPC和Docker中的应用。

系列文章: DevOps
  1. 1 API网关是什么?微服务的统一入口点
  2. 2 NAT是什么?计算机网络中的网络地址转换详解
  3. 3 GitLab CI/CD是什么?自动化构建、测试与部署流水线
  4. 4 Apache Kafka是什么?分布式事件流处理平台详解
  5. 5 Serverless是什么?FaaS、冷启动与何时选择无服务器架构
  6. 6 Subnet和CIDR是什么?IP网络分段与现代路由
  7. 7 什么是Kubernetes?当今最流行的容器编排平台
  8. 8 Proxy是什么?正向代理、反向代理与SOCKS5详解
  9. 9 什么是Nginx?集Web服务器、反向代理与负载均衡于一体
✦ 快速摘要
NAT(网络地址转换)是一种让多台设备共用一个公网IP地址的技术。深入了解PAT、静态NAT、动态NAT的工作原理,以及NAT在路由器、云端VPC和Docker中的应用。
这篇文章怎么样?

NAT(网络地址转换)是一种网络技术,让数百万家庭和办公室设备共享单个公网IP地址——这是解决IPv4地址耗尽问题的实际方案。本文解释NAT是什么、PAT的工作机制,以及NAT在家庭路由器、云端VPC和Docker中的应用。

NAT是什么?

**NAT(Network Address Translation,网络地址转换)**是路由器或防火墙在数据包通过设备时修改数据包头部IP地址的过程。最初目标:允许局域网内的多台设备共享单个公网IP地址与互联网通信。

1996年,IANA预测IPv4地址将会耗尽——他们是对的(实际发生于2011年)。NAT成为"救生筏",通过将私有地址空间与公共互联网隔离,将IPv4的生命周期延长了15年以上。

私有IP地址范围(无法在互联网上路由):

  • 10.0.0.0/8 — A类,最多1600万个内网地址
  • 172.16.0.0/12 — B类,常用于中型企业网络
  • 192.168.0.0/16 — C类,家庭网络最常见(65,536个地址)

局域网内的设备可以使用这些范围内的任意地址,无需向IANA注册,因为它们永远不会直接出现在公共互联网上——NAT在边界处理地址转换。

NAT的3种主要类型

静态NAT(Static NAT)

一对一固定映射:一个私有IP始终对应同一个固定公网IP。适合需要稳定可达地址的Web服务器和邮件服务器,以便外部客户端可以主动发起连接。

示例:192.168.1.10203.0.113.10(永久、双向)

动态NAT(Dynamic NAT)

路由器维护一个公网IP 地址池,需要时临时分配给设备。设备断开连接后,IP归还地址池。如今较少使用,因为仍需要多个公网IP——无法实现PAT的多对一效率。

PAT — 端口地址转换(NAT伪装)

这是最常见的类型——多个私有IP共享单个公网IP,通过端口号加以区分。在Linux上也称为"IP伪装"(IP Masquerading),在Cisco上称为"NAT超载"(NAT Overload)。

几乎所有家庭路由器和大多数企业路由器都使用PAT。单个公网IP的路由器可以通过在不同源端口号上多路复用连接,同时为数十台设备提供服务。TCP/UDP端口范围从0到65535,每个公网IP有数万个槽位可用。

PAT工作原理详解

192.168.1.10的计算机向8.8.8.8:53发送DNS查询时:

  1. 原始数据包离开设备:src=192.168.1.10:52341,dst=8.8.8.8:53
  2. 路由器重写源地址:src=203.0.113.1:40001,dst=8.8.8.8:53
  3. 路由器记录到NAT表192.168.1.10:52341 ↔ 203.0.113.1:40001
  4. DNS响应到达路由器:dst=203.0.113.1:40001
  5. 路由器查找NAT表 → 转发至192.168.1.10:52341

NAT表是有状态的——路由器跟踪每个活动连接。连接结束或超时(UDP通常30秒,TCP建立连接通常120秒)后,条目被删除,端口槽位重新可用。

多台设备可以在内部使用相同的源端口(例如192.168.1.10:52341192.168.1.20:52341)——路由器为每个分配不同的外部端口(4000140002)并分别映射。这是PAT的核心:外部端口号成为唯一的会话标识符。

Linux上使用iptables配置NAT

Linux可以使用iptables作为完整的NAT路由器运行。这种配置常用于家庭实验室、云端网关实例或自托管VPN出口节点:

Bash
 1# 启用IP转发(允许Linux在接口之间转发数据包)
 2echo 1 > /proc/sys/net/ipv4/ip_forward
 3
 4# 通过sysctl持久化配置(重启后生效)
 5echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
 6sysctl -p
 7
 8# NAT伪装:内网所有流量通过eth0出口
 9iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
10
11# 端口转发(DNAT):将外部8080端口路由到内部192.168.1.10:80
12iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
13  -j DNAT --to-destination 192.168.1.10:80
14iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT
15
16# 持久化规则(重启后保留)
17iptables-save > /etc/iptables/rules.v4

查看当前NAT状态:

Bash
 1# 查看连接跟踪表(所有活动NAT映射)
 2conntrack -L
 3# 或直接从内核读取
 4cat /proc/net/nf_conntrack
 5
 6# 查看所有iptables NAT规则
 7iptables -t nat -L -n -v
 8
 9# 统计活动NAT条目数量
10conntrack -L | wc -l

conntrack命令显示每个被跟踪的活动会话,包括协议、状态、超时时间以及原始/回复地址元组。这是可以在运行中的Linux路由器上实时检查的NAT表。

Docker中的NAT

Docker在bridge网络中启动容器时会自动创建NAT规则:

Bash
 1# 检查Docker默认bridge网络
 2docker network inspect bridge
 3
 4# 查看Docker创建的iptables NAT规则
 5sudo iptables -t nat -L DOCKER -n -v
 6
 7# 端口映射(-p 8080:80)自动创建DNAT规则
 8docker run -p 8080:80 nginx
 9# 等效于:
10# iptables -t nat -A DOCKER -p tcp --dport 8080 -j DNAT --to 172.17.0.2:80

bridge网络中的容器默认从172.17.0.0/16范围获取IP。当容器向外发送流量时,Docker宿主机执行MASQUERADE——将容器IP替换为宿主机IP。发布端口的入站流量通过DNAT直接转发到容器的私有IP和端口。

检查Docker创建的规则:

Bash
1# 查看POSTROUTING链中的所有NAT规则(包括Docker MASQUERADE)
2sudo iptables -t nat -L POSTROUTING -n -v
3
4# 查看通过Docker NAT的活动连接
5sudo conntrack -L | grep 172.17

使用docker network create创建的自定义Docker网络也默认使用NAT,但子网不同(如172.18.0.0/16172.19.0.0/16)。这使不同网络上的容器可以相互隔离,同时仍共享宿主机的公网IP进行出站流量。

云端NAT(AWS VPC)

AWS VPC使用**NAT网关(NAT Gateway)**让私有子网资源无需公网IP即可访问互联网:

流量路径: 私有子网EC2 → NAT Gateway(位于公有子网)→ Internet Gateway → 互联网

AWS NAT Gateway特点:

  • 绑定弹性IP(静态公网IP)——便于与第三方服务进行IP白名单配置
  • 全托管服务——AWS自动扩展,无需运维
  • 按小时计费(约$0.045/小时)加数据处理费(约$0.045/GB)
  • 可用区级别——为保证高可用性,需在每个可用区部署一个NAT Gateway

Terraform示例:

hcl
 1resource "aws_eip" "nat" {
 2  domain = "vpc"
 3}
 4
 5resource "aws_nat_gateway" "main" {
 6  allocation_id = aws_eip.nat.id
 7  subnet_id     = aws_subnet.public.id
 8
 9  tags = {
10    Name = "main-nat-gateway"
11  }
12}
13
14resource "aws_route" "private_internet" {
15  route_table_id         = aws_route_table.private.id
16  destination_cidr_block = "0.0.0.0/0"
17  nat_gateway_id         = aws_nat_gateway.main.id
18}

其他云服务提供商也有类似服务:Google Cloud NATAzure NAT GatewayDigitalOcean NAT Gateway均基于相同原理运作——为需要出站互联网访问但不暴露入站连接的私有资源提供托管NAT。

NAT的问题:NAT穿透

NAT阻断入站连接——外部主机无法主动连接到NAT后的设备,因为没有方法访问私有IP。这在实际应用中带来了挑战:

  • VoIP和视频通话:WebRTC需要低延迟的直接P2P连接。解决方案:STUN(发现公网IP/端口)、TURN(P2P失败时中继流量)和ICE(按优先级尝试所有候选路径的框架)
  • P2P游戏:NAT后的游戏主机需要"打洞"(hole punching)——双方同时向对方发送数据包,在对方的数据包到达之前在NAT表中打开条目
  • 自托管服务器:需要在路由器配置中进行端口转发,或使用VPN反向隧道(Cloudflare Tunnel、ngrok、Tailscale funnel)完全绕过NAT
  • 对称NAT(Symmetric NAT):最严格的NAT类型——为每个目标分配不同的外部端口,使基于STUN的P2P不可靠。WebRTC将回退到TURN中继,增加延迟和服务器成本

NAT类型分类(从最宽松到最严格):

  1. 全锥形NAT(Full Cone NAT)——映射建立后,任何外部主机都可以到达内部客户端
  2. 受限锥形NAT(Restricted Cone NAT)——只有客户端曾联系过的主机才能发送入站数据包
  3. 端口受限锥形NAT(Port Restricted Cone NAT)——只有客户端联系过的确切IP:端口才能回复
  4. 对称NAT(Symmetric NAT)——每个目标使用不同的外部端口;单独使用STUN不够

NAT64:连接IPv4与IPv6

随着互联网向IPv6过渡,NAT64允许纯IPv6客户端访问纯IPv4服务器:

  • IPv6客户端 → NAT64网关 → IPv4服务器
  • NAT64网关在边界将IPv6数据包转换为IPv4,反之亦然
  • 结合DNS64使用,为纯IPv4域名合成IPv6地址,使客户端无需了解底层IPv4基础设施

NAT64正越来越多地被移动运营商和企业网络部署,这些网络内部已迁移到纯IPv6,但仍需访问传统IPv4服务。苹果要求iOS应用在NAT64环境中正常运行,这也是应用开发者必须测试IPv6兼容性的原因。

Subnet和CIDR是什么?IP网络分段详解

VPN是什么?虚拟专用网络详解

Kubernetes是什么?容器编排详解

常见问题Q&A
NAT是什么?简单来说?
NAT(网络地址转换)是一种让路由器将局域网内设备的私有IP地址转换为单个公网IP地址的技术,用于与互联网通信。这就是为什么数十亿台设备可以连接互联网,尽管IPv4只有约43亿个地址。
PAT和静态NAT有什么区别?
静态NAT是固定的一对一映射:一个私有IP始终对应同一个公网IP——通常用于需要从互联网访问的服务器。PAT(端口地址转换),也称为NAT伪装,通过端口号区分连接,将多个私有IP映射到同一个公网IP——这是家庭路由器和企业路由器中最常见的NAT类型。
NAT会影响网络性能吗?
会,但对现代硬件来说通常可以忽略不计。路由器需要维护NAT转换表并查找每个数据包。NAT真正的挑战在于:(1) P2P/VoIP/游戏需要入站连接,NAT穿透较为复杂;(2) 全锥形NAT与对称NAT的行为差异影响WebRTC;(3) NAT表对同时连接数量有限制。
Docker如何使用NAT?
Docker桥接网络默认使用NAT(iptables MASQUERADE),使容器能够访问互联网。容器从172.17.0.0/16网段获取私有IP。当容器向外发送数据包时,Docker守护进程使用iptables MASQUERADE将容器的源IP替换为Docker宿主机的IP。端口映射(-p 8080:80)会创建DNAT规则,将流量转发到容器。
IPv6还需要NAT吗?
理论上不需要——IPv6拥有340万亿亿亿个地址,足以为地球上每个原子分配一个。然而,NAT66(IPv6的NAT)仍然存在于某些企业部署中,原因是安全需求(隐藏内网拓扑)或ISP只分配了一个小的IPv6前缀。趋势是采用端到端IPv6,无需NAT。
什么是NAT穿透?
NAT穿透是一组技术,用于让两台位于NAT后的设备能够直接连接——因为NAT默认阻止入站连接。常见技术包括:STUN(发现公网IP/端口)、TURN(P2P失败时的中继服务器)和ICE(WebRTC中使用的结合STUN+TURN的框架)。VoIP、WebRTC和点对点游戏都依赖NAT穿透。

NAT (Network Address Translation) is the networking technique that lets millions of home and office devices share a single public IP address — the practical solution to IPv4 address exhaustion. This article explains what NAT is, how PAT works step by step, and how NAT operates in home routers, cloud VPCs, and Docker.

What is NAT?

NAT (Network Address Translation) is the process by which a router or firewall modifies IP addresses in packet headers as those packets pass through the device. The original goal: allow multiple devices on a private network to share a single public IP address when communicating with the internet.

In 1996, IANA predicted IPv4 would run out — and they were right (it happened in 2011). NAT became the "life raft" that extended IPv4's lifespan by 15+ years by separating the private address space from the public internet.

Private IP ranges (not routable on the public internet):

  • 10.0.0.0/8 — Class A, up to 16 million internal addresses
  • 172.16.0.0/12 — Class B, commonly used in mid-size enterprises
  • 192.168.0.0/16 — Class C, ubiquitous in home networks (65,536 addresses)

Devices on a local network can use any address in these ranges without registering with IANA, because they never appear directly on the public internet — NAT handles the translation at the boundary.

3 Types of NAT

Static NAT

A 1-to-1 fixed mapping: one private IP always corresponds to one fixed public IP. Ideal for web servers and mail servers that need a stable, reachable address so external clients can initiate connections.

Example: 192.168.1.10203.0.113.10 (permanent, bidirectional)

Dynamic NAT

The router maintains a pool of public IPs and temporarily assigns one to a device when it needs internet access. When the device disconnects, the IP returns to the pool. Less common today because it still requires multiple public IPs — you don't get the many-to-one efficiency of PAT.

PAT — Port Address Translation (NAT Masquerade)

This is the most common type — many private IPs share a single public IP, distinguished by port number. Also called "IP Masquerading" on Linux or "NAT Overload" on Cisco IOS.

Virtually every home router and most enterprise routers use PAT. A router with a single public IP can simultaneously serve dozens of devices by multiplexing connections across different source port numbers. TCP/UDP ports range from 0–65535, giving the router tens of thousands of slots per public IP.

How PAT Works: Step-by-Step

When a computer at 192.168.1.10 sends a DNS query to 8.8.8.8:53:

  1. Original packet leaves device: src=192.168.1.10:52341, dst=8.8.8.8:53
  2. Router rewrites source: src=203.0.113.1:40001, dst=8.8.8.8:53
  3. Router records in NAT table: 192.168.1.10:52341 ↔ 203.0.113.1:40001
  4. DNS response arrives at router: dst=203.0.113.1:40001
  5. Router looks up NAT table → forwards to 192.168.1.10:52341

The NAT table is stateful — the router tracks every active connection. When a connection ends or times out (typically 30 seconds for UDP, 120 seconds for TCP established), the entry is removed and the port slot becomes available again.

Multiple devices can use the same source port internally (e.g., both 192.168.1.10:52341 and 192.168.1.20:52341) — the router gives each a different external port (40001 and 40002) and maps them separately. This is the core insight of PAT: external port number becomes the unique session identifier.

NAT on Linux with iptables

Linux can act as a full NAT router using iptables. This configuration is common for home labs, cloud gateway instances, or self-hosted VPN exit nodes:

Bash
 1# Enable IP forwarding (allow Linux to forward packets between interfaces)
 2echo 1 > /proc/sys/net/ipv4/ip_forward
 3
 4# Persist across reboots via sysctl
 5echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
 6sysctl -p
 7
 8# NAT Masquerade: all traffic from the internal network exits via eth0
 9iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
10
11# Port forwarding (DNAT): route external port 8080 to internal 192.168.1.10:80
12iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
13  -j DNAT --to-destination 192.168.1.10:80
14iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT
15
16# Persist rules across reboots
17iptables-save > /etc/iptables/rules.v4

To inspect the current NAT state:

Bash
 1# View the connection tracking table (all active NAT mappings)
 2conntrack -L
 3# or read directly from the kernel
 4cat /proc/net/nf_conntrack
 5
 6# View all iptables NAT rules
 7iptables -t nat -L -n -v
 8
 9# Count active NAT entries
10conntrack -L | wc -l

The conntrack command shows every active session being tracked, including protocol, state, timeouts, and the original/reply address tuples. This is the live NAT table you can inspect on a running Linux router.

NAT in Docker

Docker automatically creates NAT rules when launching containers in a bridge network:

Bash
 1# Inspect Docker's default bridge network
 2docker network inspect bridge
 3
 4# View iptables NAT rules created by Docker
 5sudo iptables -t nat -L DOCKER -n -v
 6
 7# Port mapping (-p 8080:80) creates a DNAT rule automatically
 8docker run -p 8080:80 nginx
 9# Equivalent to:
10# iptables -t nat -A DOCKER -p tcp --dport 8080 -j DNAT --to 172.17.0.2:80

Containers in the bridge network receive IPs from the 172.17.0.0/16 range by default. When a container sends traffic outbound, the Docker host performs MASQUERADE — replacing the container's IP with the host's IP. Inbound traffic to published ports is DNAT-ed directly to the container's private IP and port.

You can inspect what Docker has created:

Bash
1# See all NAT rules in the POSTROUTING chain (including Docker MASQUERADE)
2sudo iptables -t nat -L POSTROUTING -n -v
3
4# See active connections through Docker NAT
5sudo conntrack -L | grep 172.17

Custom Docker networks (created with docker network create) also use NAT by default, but with different subnets (e.g., 172.18.0.0/16, 172.19.0.0/16). This allows containers on different networks to be isolated while still sharing the host's public IP for outbound traffic.

NAT in Cloud (AWS VPC)

AWS VPC uses a NAT Gateway to give private subnet resources internet access without exposing them with public IPs:

Traffic flow: Private subnet EC2 → NAT Gateway (in public subnet) → Internet Gateway → Internet

AWS NAT Gateway characteristics:

  • Has an Elastic IP (static public IP) — useful for IP whitelisting with third-party services
  • Fully managed — AWS scales it automatically, no administration required
  • Billed per hour ($0.045/hour) plus data processed ($0.045/GB)
  • Zone-specific — deploy one NAT Gateway per Availability Zone for high availability

Terraform example:

hcl
 1resource "aws_eip" "nat" {
 2  domain = "vpc"
 3}
 4
 5resource "aws_nat_gateway" "main" {
 6  allocation_id = aws_eip.nat.id
 7  subnet_id     = aws_subnet.public.id
 8
 9  tags = {
10    Name = "main-nat-gateway"
11  }
12}
13
14resource "aws_route" "private_internet" {
15  route_table_id         = aws_route_table.private.id
16  destination_cidr_block = "0.0.0.0/0"
17  nat_gateway_id         = aws_nat_gateway.main.id
18}

Other cloud providers have equivalent services: Google Cloud NAT, Azure NAT Gateway, and DigitalOcean NAT Gateway all function on the same principles — managed NAT for private resources that need outbound internet access without inbound exposure.

The NAT Traversal Problem

NAT blocks inbound connections — an external host cannot initiate a connection to a device behind NAT because it has no way to reach the private IP. This creates real-world challenges:

  • VoIP & video calls: WebRTC needs direct P2P connections for low-latency audio/video. Solution: STUN (discovers public IP/port), TURN (relays traffic when P2P fails), and ICE (framework that tries all candidate paths in priority order)
  • P2P gaming: Game consoles behind NAT need "hole punching" — both endpoints simultaneously send packets to each other to open NAT table entries before the other's packet arrives
  • Self-hosted servers: Require port forwarding in the router config, or a VPN reverse tunnel (Cloudflare Tunnel, ngrok, Tailscale funnel) that bypasses NAT entirely
  • Symmetric NAT: The strictest NAT type — allocates a different external port for each destination, making STUN-based P2P unreliable. WebRTC falls back to TURN relay, which increases latency and server costs

NAT type classification (from most permissive to most restrictive):

  1. Full Cone NAT — any external host can reach the internal client after a mapping is established
  2. Restricted Cone NAT — only hosts the client has contacted can send inbound packets
  3. Port Restricted Cone NAT — only the exact IP:port the client contacted can reply
  4. Symmetric NAT — different external port per destination; STUN alone is insufficient

NAT64: Bridging IPv4 and IPv6

As the internet transitions to IPv6, NAT64 allows IPv6-only clients to reach IPv4-only servers:

  • IPv6 client → NAT64 gateway → IPv4 server
  • The NAT64 gateway translates IPv6 packets into IPv4 and vice versa at the boundary
  • Combined with DNS64, which synthesizes IPv6 addresses for IPv4-only domain names, so clients never need to know about the underlying IPv4 infrastructure

NAT64 is increasingly deployed by mobile carriers and enterprise networks that have moved to IPv6-only internally but still need to reach legacy IPv4 services. Apple requires that iOS apps work in NAT64 environments, which is why app developers must test IPv6 compatibility.

What is Subnet & CIDR? IP Network Segmentation Explained

What is VPN? Virtual Private Network Explained

What is Kubernetes? Container Orchestration Explained

Frequently Asked QuestionsQ&A
What is NAT in simple terms?
NAT (Network Address Translation) is a technique that allows a router to convert the private IP addresses of devices on a local network into a single public IP address when communicating with the internet. This is why billions of devices can connect to the internet even though IPv4 only has ~4.3 billion addresses.
How is PAT different from Static NAT?
Static NAT creates a fixed one-to-one mapping: one private IP always maps to one public IP — typically used for servers that need inbound access from the internet. PAT (Port Address Translation), also called NAT Masquerade, maps many private IPs to ONE public IP by distinguishing connections via port numbers — this is the most common NAT type used in home and enterprise routers.
Does NAT affect network performance?
Yes, but usually negligibly with modern hardware. The router must maintain a NAT translation table and look up each packet. The real challenges with NAT are: (1) NAT traversal complexity for P2P/VoIP/gaming that requires inbound connections; (2) Full Cone NAT vs Symmetric NAT behavior impacts WebRTC; (3) NAT tables have limits on the number of simultaneous connections.
How does Docker use NAT?
Docker bridge networks use NAT (iptables MASQUERADE) by default so containers can access the internet. Containers receive private IPs in the 172.17.0.0/16 range. When a container sends packets outbound, the Docker daemon uses iptables MASQUERADE to replace the container's source IP with the Docker host's IP. Port mapping (-p 8080:80) creates a DNAT rule that forwards traffic to the container.
Does IPv6 still need NAT?
In theory, no — IPv6 has 340 undecillion addresses, enough for every atom on Earth. However, NAT66 (NAT for IPv6) still exists in some enterprise deployments for security reasons (hiding internal network topology) or when an ISP only allocates a small IPv6 prefix. The trend is toward end-to-end IPv6 without NAT.
What is NAT traversal?
NAT traversal is a set of techniques that allow two devices behind NAT to connect directly — because NAT blocks inbound connections by default. Common techniques include: STUN (discovering public IP/port), TURN (relay server when direct connection fails), and ICE (a framework combining STUN+TURN used in WebRTC). VoIP, WebRTC, and peer-to-peer games all rely on NAT traversal.