In this lesson, you will learn how to transform a standard Linux host into a functional router by enabling the kernel’s packet forwarding capabilities and configuring it to act as a gateway.
The Role of IP Forwarding
By default, a Linux host acts as an "end station." If it receives an IP packet destined for an IP address other than its own, it silently drops the packet. This is a security feature to prevent unintentional routing. To turn the host into a router, we must instruct the kernel to pass these packets across network interfaces—a process known as IP forwarding.
The control mechanism for this resides in the sysctl interface. Specifically, the kernel parameter net.ipv4.ip_forward acts as the master switch. When set to 1, the kernel checks its routing table for any packet it receives, and if a path exists to the destination via a different interface, it forwards the traffic instead of dropping it.
Enabling and Verifying
To enable forwarding temporarily for the current session, use the sysctl command:
# Enable IPv4 forwarding
sudo sysctl -w net.ipv4.ip_forward=1
# For IPv6, use:
sudo sysctl -w net.ipv6.conf.all.forwarding=1
To make this change persistent across reboots, add net.ipv4.ip_forward = 1 to a configuration file in /etc/sysctl.d/.
The Gateway Configuration
Once forwarding is enabled, other hosts on your subnets need to know that your Linux machine is their exit point. You configure this by setting the default gateway on client machines to point to your Linux router’s internal IP address.
When a client wants to talk to the internet, it sends the packet to your Linux machine. Your kernel receives the packet, sees that the destination is external, and—thanks to the forwarding flag—routes it out through the external-facing interface. Note that in production scenarios, you would likely pair this with iptables or nftables for Source NAT (Masquerading) so that your internal hosts can share the public IP address of your router.
Key Takeaway: IP forwarding shifts a Linux host from a passive packet consumer to an active packet router by toggling the kernel’s net.ipv4.ip_forward flag, allowing it to bridge traffic between distinct network segments.