I'd recommend socat
instead:
echo test | socat -t 10 - tcp:server:7
(here waiting for up to 10 seconds for the server to reply and shutdown)
socat
can do much much much more than the various (different and incompatible) implementations of nc
/netcat
, and generally works more reliably. It's your ultimate plumbing Swiss Army knife.
Quoting the man page for the -t
option:
-t<timeout>
When one channel has reached EOF, the write part of the other channel is shut down. Then, socat waits [timeval] seconds
before terminating. Default is 0.5 seconds. This timeout only applies to addresses where write and read part can be closed independently. When during the timeout interval the read part gives EOF, socat
terminates without awaiting the timeout.
So above, after echo
writes test\n
, it exits, which closes the pipe. socat
sees EOF on its -
channel (stdin), then shuts the writing direction of the TCP socket and waits for the remote service to shutdown as well or for 10 seconds of inactivity whichever comes first. The echo
service is meant to terminate the connection as soon as the other end has shut down its sending direction, so that command should not take any longer than the time it takes to establish the connection, exchanging the data and shutting down.
With OpenBSD's netcat
or its port to Linux which is the default one on recent versions of Debian and derivatives at least, an approximation would be nc -Nw10 server 7
(that's different in that nc
's -w
is both a connection timeout and an inactivity timeout)
To implement a TCP echo
service on port 7777 for testing:
socat tcp-listen:7777,reuseaddr,fork exec:cat,nofork
(the fork
to fork a process for each incoming connection, nofork
to execute cat
directly in that process with its stdin/stdout being the TCP socket, like when using (x)inetd
).
Some timing on the loopback interface, with zsh
:
$ time echo test | socat -t10 - tcp:localhost:7777
test
echo test 0.00s user 0.00s system 54% cpu 0.001 total
socat -t10 - tcp:localhost:7777 0.00s user 0.01s system 55% cpu 0.009 total