September 20, 2020

How to enable IP forwarding in Linux

2 min read

IP forwarding also is known as IP routing or Internet routing is a process used to determine which path a packet or datagram can be sent. The process uses routing information to make decisions and is designed to send a packet over multiple networks.

Generally, networks are separated from each other by routers. For packets to travel between networks, they must be “routed” from one network to another. These routers contain a routing table that can contain specific instructions on how to send packets to a destination network (known as a route), or a set of generic instructions on where to send packets that do not match any of the other specified routes (called a default route), or both. These routes can either be hard-coded into the router by the network administrator (called a static route) or learned dynamically via a routing protocol. These routes give the routers instructions on how to utilize the physical network infrastructure that is in place to get packets to their destination, regardless of the number of hops that they must take to get there.

For a Linux machine to operate in router mode, IP forwarding must be enabled. To do this, enter the command:
echo “1” > /proc/sys/net/ipv4/ip_forward
after that, forwarding will work until the system reboots.
For constant forwarding, open the /etc/sysctl.conf file and change (or uncomment) the lines in it:
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1

Apply the change

sysctl p /etc/sysctl.conf

You can check if packet forwarding is enabled using the command:
cat /proc/sys/net/ipv4/ip_forward
If the result displays the number 1, then IP forwarding is enabled.
To disable IP forwarding on a running Linux system run:
echo “0” > /proc/sys/net/ipv4/ip_forward