IP in VPN vs. LAN: alias IP address by iptables

Sceneria: while your are at work you are on LAN and you use 192.168.x.x. But once you do home office you connect by VPN to the same DB and the IP changes to 10.x.x.x. And you don’t wanna change configs for your app 🙁

Using IP tables that can be worked around easily:

# Enable IP forwarding
sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'

# LAN IP
IP_LAN=192.168.3.38

# VPN IP
IP_VIRTUAL=10.8.4.38

ping -c 1 -W 1 $IP_VIRTUAL                                                 
PING 10.8.4.38 (10.8.4.38) 56(84) bytes of data.
64 bytes from 10.8.4.38: icmp_seq=1 ttl=63 time=124 ms

ping -c 1 -W 1 $IP_LAN                                                          PING 192.168.3.38 (192.168.3.38) 56(84) bytes of data.

--- 1.23.23.2 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

sudo iptables -t nat -A PREROUTING -d $IP_LAN -j DNAT --to-destination $IP_VIRTUAL
sudo iptables -t nat -A POSTROUTING -j MASQUERADE

ping -c 1 -W 1 $IP_LAN
PING 192.168.3.38 (192.168.3.38) 56(84) bytes of data.
64 bytes from 192.168.3.38: icmp_seq=1 ttl=63 time=125 ms

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.