I want to forward all the UDP packets addressed to port 1511 received on one interface (ens1) to a different machine (it is actually a docker container, but it shouldn't make any difference) at IP 172.17.0.6. I wrote this simple set of iptables rules (just an example):
#!/bin/bash
iptables --flush
iptables --table nat --flush
iptables --delete-chain
iptables --table nat --delete-chain
echo 1 > /proc/sys/net/ipv4/ip_forward
sysctl net.ipv4.ip_forward=1
modprobe ip_tables
iptables -t nat -A PREROUTING -i ens1 -p udp --dport 1511 -j DNAT --to-destination 172.17.0.6:1511
iptables -A FORWARD -p udp --dport 1511 -j ACCEPT
#iptables -A INPUT -i ens1 -p udp --dport 1511 -j DROP
iptables -A INPUT -j ACCEPT
iptables -A OUTPUT -j ACCEPT
my problem is that packets are not matched by the PREROUTING rule and are thus deliverd to the local host. I am sure that the UDP port is correct since I am running the same application on the two machines and the one on the local host regularly receives packets on port UDP 1511 (as proof, uncommenting the third rule from the bottom the local application stops receiving data). What is wrong with my script ? Thank you.
nat
table only tries to match packets that establish a new connection. If connection is already established (that is if the kernel has already seen with the same source and destination addresses and ports) when you set this rule, it just won’t work.