Even simpler using dig:
iptables -I INPUT -p tcp -s $(dig +short yourdomain.ddns.net) -m state --state NEW -m tcp -j ACCEPT
Explanation:
The dig +short yourdomain.ddns.net
is launched in a subprocess returning your IPv4 IP. The output of this subprocess is passed on to the iptables binary adding a new rule.
Note that we used -I
to prepend the rule to all others, if you want to append use -A
iptables -A INPUT -p tcp -s $(dig +short yourdomain.ddns.net) -m state --state NEW -m tcp -j ACCEPT
Update:
As MartinV states, if you keep on adding rules you could end up having a lot of duplicate rules and also reach the rule limit capacity.
The best approach would be to create a chain to hold your DDNS rules and just flush the custom chain before adding your new rule.
Create a custom chain if it doesn't exist, prepend your custom chain myDDNS to the INPUT chain to prevent being blocked by the final general REJECT in the INPUT chain and flush the chain:
iptables -N myDDNS 2>/dev/null;iptables -I INPUT -j myDDNS;iptables -F myDDNS
If the chain exists an error will be raised but the custom chain won't be duplicated. Redirecting the error to /dev/null will prevent the error from being thrown on STDIN.
Prepend your rule to your custom chain:
iptables -I myDDNS -p tcp -s $(dig +short yourdomain.ddns.net) -m state --state NEW -m tcp -j ACCEPT
Just put everything together in a one liner and call the script from the cron every N minutes.
iptables -N myDDNS 2>/dev/null;iptables -I INPUT -j myDDNS;iptables -F myDDNS && iptables -I myDDNS -p tcp -s $(dig +short yourdomain.ddns.net) -m state --state NEW -m tcp -j ACCEPT
Adding &&
between the iptables -F
(flush) and the rule prepending will make sure that the rule is added only if the flush command returns 0
ipset
, and reference that in your iptables rules. Your iptables rules will never change, but you can have an asynchronous process (i.e. a script run out of cron, or similar) that periodically looks up the address, and updates theipset
as needed. Updates in this way require no reloading of iptables rules - ipsets can be updated on-the-fly.