title: NAT
category: Networking
time: 1731246550473
---
# DNAT

Set up DNAT to forward with client source IP. 
(You may need a private tunnel as most IDCs have route filter)

    - Gateway
        - `eth0` public: `8.7.6.5`
        - `tun0` private: `10.1.1.1`
    - Backend
        - `eth0` public: `8.7.6.4`
        - `tun0` private: `10.1.1.100`

## On gateway:

```
iptables -t nat -I PREROUTING -p tcp -i eth0 --dport 8080 -j DNAT --to-destination 10.1.1.100:8080
```

## On backend:

IP Rules for special routed server

### Add a table name to `/etc/iproute2/rt_tables`

```
10 orig
```

### Add IP Rule, assuming main IP is 10.1.1.100, gateway is 10.1.1.1 (As above)

Set default route when traffic coming from NAT

```
ip rule add from 10.1.1.100 lookup orig
ip route add default via 10.1.1.1 table orig
```

OR you can add default route with default `tun0`

```
ip route add default dev tun0 table orig
```

# DNAT & SNAT

Use this if you do not need to forward client source IP.

On gateway:

```
iptables -t nat -I PREROUTING -p tcp -i eth0 --dport 8080 -j DNAT --to-destination 10.1.1.100:8080
iptables -t nat -I POSTROUTING -p tcp -o tun0 -j SNAT --to-source 10.1.1.1
```

***Reference:***
- [IP Rules - PhoenixWiki](https://wiki.phoenixlzx.com/page/IP-Rules/)
- [NAT - PhoenixWiki](https://wiki.phoenixlzx.com/page/NAT/)

