#!/bin/bash
HostName=
PortListen=
PortTarget=
IPv4=$(ping -c1 $HostName | grep "bytes of data" | cut -d "(" -f2 | cut -d ")" -f1)
echo $IPv4
# Find the command use to add previous rules
RULE2DEL1=$(iptables -t nat -S | grep '\-A PREROUTING -p tcp -m tcp --dport '$PortListen)
RULE2DEL2=$(iptables -t nat -S | grep '\-A POSTROUTING -p tcp -m tcp --dport '$PortTarget)
# Replace the -A with -D
RULE2DEL1=${RULE2DEL1/"-A"/"-D"}
RULE2DEL2=${RULE2DEL2/"-A"/"-D"}
# Delete them
iptables -t nat $RULE2DEL1
iptables -t nat $RULE2DEL2
# Add new rules
iptables -t nat -A PREROUTING -p tcp -m tcp --dport $PortListen -j DNAT --to-destination $IPv4:$PortTarget
iptables -t nat -A POSTROUTING -p tcp -m tcp --dport $PortTarget -j MASQUERADE
Forked from rikka0w0/iptables_forward_to_hostname.md
Created
November 15, 2022 01:38
-
-
Save yilmazdurmaz/cf0f05fc906296383be0e999d91b0d10 to your computer and use it in GitHub Desktop.
Add/Update iptable NAT port forward rule based on hostname instead of ip address
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment