Search code examples
linuxtcpudpnetcat

Linux - Receive data via UDP; accept TCP connections, pass the data to the clients


I have a situation in which I'm being fed data via UDP on a pre-defined port (let's say 20001).

My goal is to make that same data accessible to multiple clients, which will connect to me via TCP, again on a pre-defined port (let's say 30001).

This seems like a pretty simple thing to accomplish - but it's not exactly within my expertise. So I did some reading, and got fairly close using netcat:

nc -l -p 30001 --keep-open --sh-exec "nc -u -l 20001"

Unfortunately, this causes a new instance of the --sh-exec command to be spawned with each subsequent TCP connection, and only the first one actually 'hears' the incoming UDP data - so it has the effect that the first TCP client to connect 'wins', and any subsequent connections receive nothing, while piling up a bunch of useless processes.

I also figured piping the data into it might work:

nc -l -p 30001 --keep-open | nc -u -l 20001

But alas, it did not.

It feels like I might be attacking this problem with the wrong tool, but I'm not sure what a better/more appropriate tool for this job would be.

I welcome your thoughts!


Solution

  • If it is not bi-directional traffic you could use the following: nc -l -u -p 20001 | ncat -k -l -p 30001

    Learning from this post: How to listen for multiple tcp connection using nc it is not possible to connect multiple TCP streams to nc so they advice to use ncat.