简体   繁体   中英

Read and write to the same netcat tcp connection

Say I write to a netcat connection:

tail -f ${file} | nc localhost 7050 | do_whatever | nc localhost 7050

what happens here is that we have two socket connections, to do some request/response. But that's not ideal for a few reasons.

What I am looking to do is reuse the same connection, to read from and write to.

Does anyone know how I can reuse just one netcat connection?

The correct way to do this in UNIX is to make use of a back pipe. You can do so as follows:

First, create a pipe: mknod bkpipe p

This creates a file named bkpipe of type pipe.

Next, figure out what you need to do. Here are two useful scenarios. In these, replace the hosts/addresses and port numbers with the appropriate ports for your relay.

To forward data sent to a local port to a remote port on another machine:

 nc -l -p 9999 0<bkpipe | nc remotehost 7000 | tee bkpipe

To connect to another machine and then relay data in that connection to another:

 nc leftHost 6000 0<bkpipe | nc rightHost 6000 | tee bkpipe

If you simply need to handle basic IPC within a single host, however, you can do away with netcat completely and just use the FIFO pipe that mknod creates. If you stuff things into the FIFO with one process, they will hang out there until something else reads them out.

Using ncat is much easier and understandable for beginners as a one-liner ;)

prompt$> ncat -lk 5087 -c ' while true; do read i && echo [You entered:] $i; done'

Connect with telnet (or nc) to localhost port 5087, and everything you type echoes back to you ;) Use -lk option for listening and keeping/maintaining (multiple) connections.

You can make one bash script out of it like this, using back slashes but it invokes multiple bash, not cheap on resource usage:

#!/bin/bash
# title          : ncat-listener-bidirectional.sh
# description    : This script will listen for text entered by a client 
#                  like for instance telnet
#                  and echo back the key strokes
#
ncat -lk 5087 -c ' \
#!/bin/bash \
while true; do  \
  read i && echo [You entered:] $i; \
done'

Yeah, I think the simplest thing to do is use this method:

tail -f ${file} | nc localhost 7050 | do_whatever > ${file}

just write back into the same file (it's a 'named pipe').

As long as your messages are less than about 500 bytes, they won't interleave.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM