I am running CentOS 6.4 with OpenVZ on my laptop. In order to provide Internet access for the VEs I have to apply the following rule on the laptop:

iptables -t nat -A POSTROUTING -j SNAT --to-source <LAPTOP_IP>

It works fine.

However, I have to work in different places - office, home, partner's office etc. The IP of my laptop is different in those places, so have to alter the rule above each time I change place.

I have created a workaround which basically determines the IP and applies the rule:

IP=$(ifconfig | awk -F':' '/inet addr/&&!/{split($2,_," ");print _[1]}')
iptables -t nat -A POSTROUTING -j SNAT --to-source $IP

The workaround above works. I only still have to execute it manually. Perhaps I could make it a hook executing whenever my laptop obtains an IP address from DHCP - how can I do that?

Also, I am just wondering if there is an elegant way of getting it done in the first place - iptables? Maybe there is a syntax allowing to specify "current hardware ip addres" in the rule?


Use -j MASQUERADE (taken from CentOS docs):

To allow LAN nodes with private IP addresses to communicate with external public networks, configure the firewall for IP masquerading, which masks requests from LAN nodes with the IP address of the firewall's external device (in this case, eth0):

[root@myServer ~ ] # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

This rule uses the NAT packet matching table (-t nat) and specifies the built-in POSTROUTING chain for NAT (-A POSTROUTING) on the firewall's external networking device (-o eth0).

POSTROUTING allows packets to be altered as they are leaving the firewall's external device.

The -j MASQUERADE target is specified to mask the private IP address of a node with the external IP address of the firewall/gateway.

It was meant for uplinks which don't have static ip addresses.

  • Thank you fuero, that is almost what I wanted. However, it is not always eth0 that is used to connect to the Internet. Right at this moment I am using wlan0 and your solution worked with eth0 replaced by wlan0. Is there any way I can specify something like iptables -t nat -A POSTROUTING -o <CURRENT_INTERNET_INTERFACE> -j MASQUERADE?
    – Greendrake
    Oct 28 '13 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.