netcat: send text to echo service, read reply then exit

Just tried - slightly different behaviour between netcat-openbsd and netcat-traditional ( ubuntu 16.4). The OpenBSD variant does what you expect, while with the netcat-traditional I need to add the -q 1 to avoid waiting for more input.

echo 'test' | netcat -q 1 server 7

Your command should work. It is very similar to some of the examples in the netcat manpage.

This is exactly how netcat is supposed to operate: once it has reached EOF on stdin, it (one-way) closes the connection /to/ the server and then waits for data coming from the server. When the latter closes the connection (the other way: server->client), then netcat stops.

If your netcat command doesn't finish, I suppose there is something strange happening at the network level that keeps the echo server listening for additional input.

You can try out the -q option to force netcat to stop N seconds after EOF is encountered on stdin:

netcat -q1 server echo <<< "test"

(<<< "test" is a bashism, use your echo ... | syntax if you don't use bash)


Use this:

cat <(echo command) - | nc host port

The problem is that nc will close the connection immediately after stdin is closed, which is very quick for a simple my_command string, and thus never gets the chance to receive a response. If you pipe a very large file you will see that it might get a response before it's done sending the file.

Enter cat with - as second argument: it makes cat listen on stdin for more content to pipe through after it has sent the contents of the first argument. The first argument is just getting the echo command through cat – it could also be a file with your commands a la cat < file - | ....

The downside of that is now that it stays open until you hit ^C or ^D on the shell. Adding a timeout using -w 1 (OSX netcat) or -i 1 (nmap's ncat) makes it close the connection after 1 second, but it won't exit the process until you enter some character.

This answer is based on this answer to an identical superuser question.

Tags:

Echo

Netcat