Ubuntu – How to set the linux box as a router to forward ip packets


I am doing a network experiment about ip packet forwarding, but I don't know why it does work.

I have a linux machine with two network interfaces, eth0 and eth1 both with static IP address (eth0:, eth1:

My goal is simple, I just want to forward ip packets from eth1 with destination in subnet to eth0, and forward ip packets from eth0 with destination in subnet to eth1.

I turned on ip forwarding with:

sysctl -w net.ipv4.ip_forward=1

my routing table is like this:

# route -n
Kernel IP routing table
Destination     Gateway     Genmask        Flags Metric Ref   Use  Iface  U     0      0       0  eth0  U     0      0       0  eth1

But, when I try to ping from to, it does not work.

Best Answer

  • You need to add a forwarding rule using iptables command, something like this:

    modprobe iptable_nat
    echo 1 > /proc/sys/net/ipv4/ip_forward
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    iptables -A FORWARD -i eth1 -j ACCEPT

    see man iptables for more details, or search internet for howto articles, for example How to set up a NAT router on a Linux-based computer

    Here is Linux IP Masquerade HOWTO which discusses the topic in details.

    You should also ensure that you have no other rules (e.g. in the FORWARD chain) that are overriding the above ACCEPT rule. If there are, you probably want to delete them.

  • Related Question