Communicating with Internal NICs using iptables: Route Internet Traffic

Abstract: Enable IP forwarding and configure iptables NAT rules to route internet traffic from internal NICs through a primary external interface.

Created: 2026-07-31 by
To route internet traffic from internal network interfaces like enp2s0 and enp3s0 through a primary external interface enp1s0, you must enable IP forwarding and configure iptables NAT rules. This setup transforms your Linux machine into a router, allowing devices on the internal networks to access the outside world by masquerading their source addresses as the public IP of enp1s0.

Prerequisites for Routing

Before configuring firewall rules, ensure that the kernel is permitted to forward packets between interfaces. By default, most Linux distributions disable this feature for security reasons. You can check the current status by reading the sysctl parameter net.ipv4.ip_forward. If the value is 0, forwarding is disabled. To enable it temporarily, use the command echo 1 > /proc/sys/net/ipv4/ip_forward. For a permanent change, edit the file /etc/sysctl.conf or create a drop-in file in /etc/sysctl.d/ and set net.ipv4.ip_forward=1. Apply the changes immediately using sysctl -p. Without this step, no amount of iptables configuration will allow traffic to pass between interfaces.

Configuring NAT Rules

The core mechanism for sharing an internet connection is Network Address Translation (NAT). Specifically, you need to Masquerade outgoing traffic from the internal interfaces so that replies are correctly routed back to your Linux box. The internal interfaces enp2s0 and enp3s0 should have static or DHCP-assigned IPs on private subnets, such as 192.168.1.0/24 and 192.168.2.0/24 respectively. The external interface enp1s0 holds the public IP assigned by your ISP. You must add rules to the POSTROUTING chain of the nat table. This chain processes packets after routing decisions have been made, which is exactly when you want to modify the source address. Run the following commands to enable masquerading for both internal networks:
iptables -t nat -A POSTROUTING -o enp1s0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o enp1s0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o enp1s0 -j MASQUERADE
The first rule applies to all traffic leaving via enp1s0, while the subsequent rules explicitly target the specific source networks. In many cases, the single generic rule is sufficient, but being explicit helps with debugging and auditing. If you prefer to use SNAT instead of MASQUERADE because your public IP is static, replace MASQUERADE with SNAT --to-source YOUR_PUBLIC_IP. However, MASQUERADE is generally safer for dynamic IPs provided by ISPs.

Handling Forwarding Policies

NAT alone is not enough; you must also permit the traffic to flow through the filter table. The default policy for the FORWARD chain is often DROP or REJECT. You need to explicitly allow established connections and new connections originating from your internal networks. Add these rules to the filter table:
iptables -A FORWARD -i enp1s0 -o enp2s0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i enp1s0 -o enp3s0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i enp2s0 -o enp1s0 -j ACCEPT
iptables -A FORWARD -i enp3s0 -o enp1s0 -j ACCEPT
The first two lines allow return traffic from the internet back to your internal clients. The last two lines allow new outbound traffic from the internal NICs to the internet. Note that we do not need to explicitly allow new inbound traffic from enp1s0 to enp2s0/enp3s0 if you only intend to provide outbound internet access. If you need to host services internally, you would add additional rules for specific ports. For more details on managing connectivity issues, see Troubleshooting Home Network Connectivity Issues on Linux Computer.

Verification and Testing

Once the rules are in place, verify that they are active by running iptables -t nat -L -n -v and iptables -L FORWARD -n -v. Check the byte counters to ensure packets are being matched. From a client machine connected to enp2s0 or enp3s0, ensure the default gateway is set to the IP address of your Linux router on that specific subnet. Test connectivity by pinging an external IP address like 8.8.8.8. If ping works but web browsing fails, check DNS resolution. You may need to configure dnsmasq or forward DNS queries to your ISP's servers via iptables REDIRECT rules. It is crucial to understand that iptables rules are processed in order. If you have a preceding rule that drops traffic, your NAT and forward rules will never be reached. Always insert new rules at the appropriate position using -I instead of -A if necessary. Also, remember that these rules are lost upon reboot unless saved. Use tools like iptables-persistent or your distribution's equivalent to save the current rule set to disk. Regarding security, this configuration exposes your internal networks to the internet indirectly. While NAT provides a basic level of isolation, it is not a substitute for a proper firewall. Ensure that your internal hosts are secured against direct attacks. If you suspect malicious activity, you might need to block specific MAC addresses or IPs. For guidance on blocking unwanted sources, refer to Block MAC Address with Iptables During Attack.

Frequently Asked Questions

Why can my internal clients ping the internet but not browse websites?

This usually indicates a DNS resolution failure rather than a routing issue. Since ICMP ping uses raw sockets and bypasses standard port handling, it often works even when UDP DNS queries are blocked. Ensure your internal clients are configured with valid DNS server addresses, or add iptables rules to redirect DNS traffic to a local resolver or upstream DNS provider.

Does enabling IP forwarding expose my Linux system to attacks?

Enabling forwarding allows traffic to pass through your machine, but it does not automatically open incoming ports to the internet. However, if you misconfigure FORWARD rules to accept all traffic, attackers could potentially reach your internal networks. Always restrict FORWARD rules to only necessary traffic and keep your kernel updated to patch any networking vulnerabilities.

What happens to my iptables rules after a reboot?

By default, iptables rules are stored in memory and are lost when the system restarts. To persist them, you must save the current ruleset to a configuration file. On Debian-based systems, you can install iptables-persistent to handle this automatically during package installation or service restarts.

Can I use SNAT instead of MASQUERADE for better performance?

Yes, if your external interface enp1s0 has a static public IP address, SNAT is slightly more efficient than MASQUERADE because it does not need to look up the current IP of the interface for every packet. Replace the MASQUERADE target with SNAT --to-source your_static_public_ip. If your IP changes frequently, stick with MASQUERADE to avoid broken connections.

How do I troubleshoot if packets are not being forwarded?

First, verify that net.ipv4.ip_forward is set to 1. Second, check the FORWARD chain policies in the filter table to ensure they are not dropping traffic. Third, use tcpdump on both the internal and external interfaces to see if packets are arriving and leaving as expected. Finally, review the log output of iptables to identify which rule is matching or dropping the packets.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More