1

How do you redirect (one way only) udp packets to another host using netcat?

nc -l -u 0.0.0.0 12345 | nc -u 192.168.1.128 12345

stops after successfully redirecting the first packet.

(Note: an iptables solution would also be useful.)

Thanks,

Chris.

fadedbee
  • 2,068
  • 5
  • 24
  • 36

2 Answers2

2

For the iptables solution, you'll basically be doing an destination NAT on the packets. Something like:

iptables -t nat -I PREROUTING -p udp --dport 12345 -j DNAT --to 192.168.1.128:12345

With netcat, hmm. You can use the -k option to keep the listen side up after you process the packets, but you'll need to do something to keep sending. Named pipes, maybe?

mknod /tmp/nc.pipe p
nc -l -k -u 0.0.0.0 12345 > /tmp/nc.pipe &

while [1]
do
  nc -u 192.168.1.128 12345 < /tmp/nc.pipe
done

Untested, clearly.

cjc
  • 24,916
  • 3
  • 51
  • 70
0

So long as you don't receive more than one message per second, this will forward 99%+ of them.

(It's a really horrible fudge.)

#!/bin/bash 
while :
do
  bash -c "nc -l -u 0.0.0.0 12345 | nc -u 192.168.1.128 12345" &
  sleep 1
  kill $!
done
fadedbee
  • 2,068
  • 5
  • 24
  • 36
  • I observe a rather strange behaviour here. I use `bash -c "nc -lu 127.0.0.1 47556 | nc -u 192.168.10.1 47555" &` and this leads to spawning `netcat` processes but not actually killing them afterwards. I noticed this after several crashes of my embedded system (limited resources) and called `netstat -tulpn` to see if it's not related to that script. I saw A LOT of `nc` processes. Strangely enough calling `bash -c "nc -lu 47555 | nc -u 127.0.0.1 475559" &` properly cleans up the spawned `nc` processes. I wonder why. – rbaleksandar May 02 '18 at 14:14