Network and Port Forwarding on Linux

In Linux systems, such as Ubuntu, how can we achieve data forwarding for multiple network connections and port forwarding? The following will explain these two scenarios separately:1. Dual Network Card NAT Networking

In Linux, there are two WiFi modules (one for 2.4GHz and the other for dual-band 2.4GHz+5GHz). The router operates on 2.4GHz, while other receiving devices experience unstable data processing on 2.4GHz. Therefore, we want to switch to 5GHz for testing. We connect both WiFi modules to the PC (via USB interface). When the drivers are successfully loaded, wlan0 and wlan1 will be mapped. The configuration of AP and STA will not be discussed here; instead, we will focus on how to enable IP forwarding between wlan0 (2.4G, connected to the external network, acting as STA) and wlan1 (dual-band, connected to the internal network, acting as AP). This is quite simple; just execute the following commands:

echo 1 > /proc/sys/net/ipv4/ip_forwardiptables -A FORWARD -i wlan1 -o wlan0 -m state --state ESTABLISHED,RELATED -j ACCEPTiptables -A FORWARD -i wlan1 -o wlan0 -j ACCEPTiptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

The first command is very important; it enables the IP forwarding feature. The next three commands add routing rules (the last two are sufficient).

According to http://www.revsys.com/writings/quicktips/nat.html, the above commands should be modified to:

echo 1 > /proc/sys/net/ipv4/ip_forwardiptables -A FORWARD -i wlan0 -o wlan1 -m state --state ESTABLISHED,RELATED -j ACCEPTiptables -A FORWARD -i wlan1 -o wlan0 -j ACCEPTiptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

2. Local Port Forwarding

To perform local port forwarding in Linux, you can follow these steps:

  • Ensure that the NetFilter related Linux kernel modules are compiled into the kernel and include the following configuration:

    CONFIG_IP_NF_TARGET_REDIRECT=y
  • Enable the forwarding feature:

    echo '1' > /proc/sys/net/ipv4/ip_forward
  • Set forwarding rules:

    iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8000

After executing the above commands, any machine accessing the 80 port service of this machine will be redirected to the service on port 8000.

Leave a Comment