Skip to content

Instantly share code, notes, and snippets.

@benkoshy
Last active November 14, 2023 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkoshy/e50e47f60f5c735f157fb86404621b30 to your computer and use it in GitHub Desktop.
Save benkoshy/e50e47f60f5c735f157fb86404621b30 to your computer and use it in GitHub Desktop.
How to enable a port forwarding script - with iptables
#!/bin/bash

echo 1 > /proc/sys/net/ipv4/ip_forward # must be enabled for the forwarding to work

iptables -F 
iptables -t nat -F  # flush the nat table
iptables -t mangle -F
iptables -X


# Source
# https://serverfault.com/questions/765071/iptables-forward-all-traffic-to-a-specified-port-to-another-device

## TCP

# we want to forward from the linux_machine to the windows_server

windows_server='192.168.128.18'
linux_machine='192.168.128.7'

iptables -t nat -A PREROUTING -p tcp --dport 1237 -j DNAT --to-destination $windows_server:1237
iptables -t nat -A POSTROUTING -p tcp -d $windows_server --dport 1237 -j SNAT --to-source $linux_machine

iptables -t nat -A PREROUTING -p tcp --dport 1238 -j DNAT --to-destination $windows_server:1238
iptables -t nat -A POSTROUTING -p tcp -d $windows_server --dport 1238 -j SNAT --to-source $linux_machine

echo -e $(iptables --table nat --list)

# to run
# sudo ./port_forwarding.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment