Port forwarding on local host

Posted on In QA, Tutorial

I am trying to forward UDP port 500 to 2500 on local host, but can’t get this to work – I have run:
iptables -t nat -A PREROUTING -p udp -d 192.168.1.10 –dport 500 -j DNAT –to-destination 192.168.1.10:2500
iptables -A FORWARD -p udp -d 192.168.1.10 –dport 2500 -j ACCEPT

where 192.168.1.10 is the IP of my local host, but if in one session I run netcat:
nc -u 192.168.1.10:500
and in a 2nd sessions run:
nc -l -u 500
and a 3rd session run:
nc -l -u 2500

then data I enter in session 1 is received on session 2, not session 3, so packets are not being forwarded. I did have this working, but I didn’t make rules persistent and after rebooting I can’t get this to work:
# cat /proc/sys/net/ipv4/ip_forward
1
# iptables -t nat -S;iptables -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-A PREROUTING -d 192.168.1.10/32 -p udp -m udp –dport 500 -j DNAT –to-destination 192.168.1.10:2500
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A FORWARD -d 192.168.1.10/32 -p udp -m udp –dport 2500 -j ACCEPT

What am I missing?


For redirecting of packets to a port to another localhost’s port, you can use ‘REDIRECT’ instead of DNAT:

(using 10.8.1.200 as one example)

iptables -t nat -A PREROUTING -d 10.8.1.200/32 -p udp -m udp --dport 500 -j REDIRECT --to-ports 2500

If you would like to make your localhost to use 10.8.1.200:2500 too, you need one additional OUTPUT rule:

iptables -t nat -A OUTPUT -d 10.8.1.200/32 -p udp -m udp --dport 500 -j REDIRECT --to-ports 2500

Overall:

# iptables -t nat -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-A PREROUTING -d 10.8.1.200/32 -p udp -m udp --dport 500 -j REDIRECT --to-ports 2500
-A OUTPUT -d 10.8.1.200/32 -p udp -m udp --dport 500 -j REDIRECT --to-ports 2500

Cheers.


Thanks this worked, and it works adding OUTPUT rule for the DNAT & FORWARD rules in my OP or using REDIRECT as in your post.

Thanks

Mike

Leave a Reply

Your email address will not be published. Required fields are marked *