Variable host IP address in iptables rule

Posted by DrakeES on Server Fault See other posts from Server Fault or by DrakeES
Published on 2013-10-28T03:28:49Z Indexed on 2013/10/28 3:56 UTC
Read the original article Hit count: 174

Filed under:
|
|

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:

#!/bin/bash
IP=$(ifconfig | awk -F':' '/inet addr/&&!/127.0.0.1/{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?

© Server Fault or respective owner

Related posts about iptables

Related posts about nat