[LINUX] Translate IP address range to another subnet 1: 1

Thing you want to do

I connected two networks, but I can't set the routing directly because of the duplicate IP address. Therefore, I want to convert the connection destination IP to an unused IP range.

Assumed network

Two Linux servers GW1 and GW2 were connected to communicate Host H1 ( and H2 ( However, since the subnet to which H2 belongs is used by Network 2, it is not possible to set the routing directly to GW1 for communication.

(Network 1)
    .10  .1     .1
[H1]======================[ GW1 ]================
                       eth1 ||  .1  .10   
                          [ GW2 ]====================[H2] 
(Network 2)


By using iptables NETMAP, the IP address of H2 seen from Network 1 is converted to another subnet that is not used by Network 1.

Former story https://serverfault.com/questions/109569/iptables-massive-11-nat

Here, address translation is performed so that the host on the subnet to which H2 belongs can be accessed with 192.0.2.x / 24.

Address translation ( <->

Add the following settings to GW2.

iptables -t nat -A PREROUTING -d -i eth1 -j NETMAP --to
iptables -t nat -A POSTROUTING -s -o eth1 -j NETMAP --to

In order to limit the range of destinations for address translation to Network 1, the target is limited by the connected interface. Without this, the address will be translated to another subnet in Network2.


Add static routing. Set the routing to in GW1

ip route add via

Set the routing for in H1 as well. (Not required if GW1 is the default gateway)

Set the routing for in GW2.

ip route add via

Set the routing for in H2 as well. (Not required if GW1 is the default gateway)

With the settings up to this point, H1 and H2 can communicate.

Communication from H1 to H2: Specify the converted address

h1$ ping 
h1$ ssh

Communication from H2 to H1: Specify the address of H1 as it is

h2$ ping 
h2$ ssh 1192.168.30.10

In H1, the communication from H2 appears as the communication connected from after conversion.

Note: When communication is H1-> H2 one-way

If communication is started only in the direction from H1 to H2, setting SNAT in GW2 eliminates the need for routing settings on the H2 side. In this case, in H2, the communication from H1 looks like a connection from GW2.

Add the following to GW2

iptables -t nat -A POSTROUTING -d -j SNAT --to-source is the IP address of GW2


Articles on SNAT / DNAT that rewrite IPs destined for a single host can be found in various places, but I could not find an article on how to replace the IP address of the entire subnet range, so I summarized it here.

Recommended Posts

Translate IP address range to another subnet 1: 1
Convert IP address to decimal
To get a local IP address programmatically
Note to plot IP address with Kibana + Elasticsearch
Added firewalld to Amazon Linux 2 (IP address restrictions)
Get local IP address