Skip to content

Instantly share code, notes, and snippets.

@FelixWolf
Created March 4, 2021 09:25
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 FelixWolf/d624d1c24eb1ad99d9d7beca68cdcd42 to your computer and use it in GitHub Desktop.
Save FelixWolf/d624d1c24eb1ad99d9d7beca68cdcd42 to your computer and use it in GitHub Desktop.
Local nat loopback
#!/usr/bin/env bash
#Set this to the address to rewrite to:
NewAddress=192.168.0.127
#This pulls the ip from ipify.org:
CurrentAddress=$(wget -qO- https://api.ipify.org)
#Initialize a empty variable containing the lines to delete
lines=""
#Iterate over the iptables result(at end of the loop)
while read -r line ; do
#Search for the NatLoopback comment
if [[ $line == *"/* NatLoopback */"* ]]; then
#If $lines is empty, don't preprend a space
if [[ $lines == "" ]]; then
lines="${line%% *}"
#Else, pre-pend the line (In a reverse array fashion)
else
lines="${line%% *} $lines"
fi
fi
done <<< $(iptables -t nat -L --line-numbers)
#Iterate over each line number in $lines
for line in $lines; do
#Delete that line
iptables -t nat -D OUTPUT $line
done
#Add the new IP forward into iptables
iptables -t nat -A OUTPUT -p tcp -d $CurrentAddress -j DNAT --to-destination $NewAddress -m comment --comment "NatLoopback"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment