I want to read the data arriving on a specific TCP port indefinitely
This doesn't really make sense... if you were after all data arriving on a UDP port, then fine - TCP however is a connection-based protocol. Once a client connects, and you accept()
, you end up with two sockets - one listening, and one connected to the client... nc
will close the original listening socket, and deal one-on-one with the client.
If you'd like to be able to listen for multiple clients connecting, then try using socat
:
socat TCP-LISTEN:12345,fork FD:1 >> ../myfile
This will setup a listening socket and fork a new process on connection - keeping the listening socket listening. All data received will be written to stdout (file descriptor 1
), which is redirected to ../myfile
for appending.
NOTE: data will be received from any number of clients, in no guaranteed order with no framing... i.e: it'll be a mess of jumbled data if you have more than one client at a time.
If you want socat
to handle the file for you, then you can use one of CREATE
or OPEN
(see the man page):
socat TCP-LISTEN:12345,fork OPEN:../myfile,append
If you are content with a "one client at a time" approach, then put nc
in a loop:
while :; do nc -l 12345; done >> ../myfile
Test this with nc
:
nc localhost 12345
What was your intention with using
-v
and-p
? – Attie – 2018-06-06T15:53:55.403@Attie -v to see what it is receiving and -p for port number. – user422171 – 2018-06-06T16:13:55.513
Yes, but why would that be useful to try and make it keep listening? – Attie – 2018-06-06T16:15:44.193
@Attie It was just for testing the command if it works and to know how it works. Was gonna remove it eventually.. – user422171 – 2018-06-06T16:39:15.153