2

What I want:

Incoming TCP and UDP connections on port 900 from the resolving IP address of myip.dyndns.org (dynamic IP) should redirect to port 5050 on the local machine. All other IP addresses should "remain" on port 900.

I've read that iptables only resolve the IP address once the rule is added and then uses that IP address even if it changes and I found a script to run with crontab to solve this:

#!/bin/bash

HOSTNAME=myip.dyndns.org
LOGFILE=iptables_update.log

Current_IP=$(host $HOSTNAME | cut -f4 -d' ')

if [ $LOGFILE = "" ] ; then
  iptables -t nat -I PREROUTING -p tcp --src $Current_IP --dport 900 -j REDIRECT --to-port 5050
  iptables -t nat -I PREROUTING -p udp --src $Current_IP --dport 900 -j REDIRECT --to-port 5050
  echo $Current_IP > $LOGFILE
else

  Old_IP=$(cat $LOGFILE)

  if [ "$Current_IP" = "$Old_IP" ] ; then
    echo "Update not required."
  else
    iptables -t nat -D PREROUTING -p tcp --src $Old_IP --dport 900 -j REDIRECT --to-port 5050
    iptables -t nat -D PREROUTING -p udp --src $Old_IP --dport 900 -j REDIRECT --to-port 5050
    iptables -t nat -I PREROUTING -p tcp --src $Current_IP --dport 900 -j REDIRECT --to-port 5050
    iptables -t nat -I PREROUTING -p udp --src $Current_IP --dport 900 -j REDIRECT --to-port 5050
    echo $Current_IP > $LOGFILE
    echo "Updating iptables with IP:" $CurreIP
  fi
fi

So my only question is if this is a OK/correct way of accomplishing this?

Thanks in advance!

1
  • Another thing is you shouldn't use two rules successively as -I prerouting because this would overwrite the 1st rule as the default when no rule number is given in the chain,use -A instead for the 2nd rule's I. See man iptables for details.
    – heemayl
    Oct 16, 2014 at 20:11

0

You must log in to answer this question.

Browse other questions tagged .