How to set up port forwarding on Ubuntu 22.04/Debian11

Preface

As a netizen, you may use TCP port forwarding in the following situations:

  1. Bypassing network restrictions: Some countries or regions may restrict access to specific websites or services, and TCP port forwarding can help users access these blocked websites or services through an intermediate machine. For example, in India/Saudi, the government has blocked social media and communication applications several times, and TCP port forwarding can help users bypass these restrictions.
  2. Accelerating network connections: Internet infrastructure in India is relatively inadequate, and accessing foreign websites or services may be affected by speed and stability issues. TCP port forwarding can improve the speed and stability of network connections by forwarding network traffic to faster hosts or ports through an intermediate machine.
  3. Bypassing geographic restrictions: Some online games or streaming services may restrict user access due to geographic location, and TCP port forwarding can disguise user geographic location through an intermediate machine to bypass geographic restrictions. For example, Indian users who want to watch American video streaming services can use TCP port forwarding to bypass geographic restrictions.

Brief

This article will show you,

  1. how to redirect traffic to another server; and,
  2. how to connect to a computer in private LAN from outside; and,
  3. how to bypass geographic restrictions by port forwarding.

This can be done within 1 min.

Take Action!

Suppose you want every traffic towards 99.99.99.99:9999 to be redirected to 11.11.11.11:1111. You should log into 99.99.99.99 as root, and copy and run commands below (IPs should be replaced to real ones accordingly):

# make sure we have installed `iptables`
sudo bash -c 'which iptables || (apt update && apt install -y iptables)'

# setting up DNAT, so that every packet torwards 99.99.99.99:9999 will be redirected to 11.11.11.11:1111
sudo iptables -t nat -A PREROUTING -p tcp --dport 9999 -j DNAT --to-destination 11.11.11.11:1111

# enabling the masquerade
sudo iptables -t nat -A POSTROUTING -j MASQUERADE

# enable IPv4 forwarding, 
sudo bash -c 'echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf && sysctl -p'

# print the changes
sudo iptables -nL -t nat

If everything goes well, we should find a similar result like:

You are all set! Please note, the port forwarding won’t survive from a reboot with commands above. To apply the change permanently, you may refer to another tutorial here.

Please note that using TCP port forwarding may have security risks, so it’s important to have adequate understanding and evaluation before using it. In addition, using TCP port forwarding may violate some laws and regulations in certain countries or regions, so use it with caution.

Leave a Reply

Your email address will not be published. Required fields are marked *