Netcat sure is a handy utility, but there's one minor problem I've come across, for which I'm offering the following simple fix. First, the explanation why I think the fix is a good idea: Netcat doesn't drop the connection until the server closes it so that you don't ever lose the final output from the server, which is what may happen if the client simply closes the connection when the client reads EOF from stdin. This is good, and I'm not suggesting that it change. However, a deadlock occurs if the server doesn't close its end until it reads EOF on the connection. For example, if you netcat to the "echo" service (on port 7), sending EOF (by hitting CTRL-D or whatever, say) won't ever cause netcat to exit; it will simply stop reading its stdin, and the server will keep waiting for more input, which will never arrive. Some protocols (e.g. http) avoid this problem by signalling EOF in-band, but I don't think netcat should make this assumption. The solution is easy: use shutdown to tell the server that the client has finished writing, but can keep on reading. Servers like "echo", which wait for EOF from the client will then gracefully close their end of the connection, causing netcat to exit with no loss of data. I'd be interested in anyone's feedback; I reckon this simple patch makes netcat an even more useful program. *** netcat-1.10.orig/netcat.c Thu Mar 21 11:38:04 1996 --- netcat-1.10.greyham/netcat.c Mon Sep 13 10:38:14 1999 *************** *** 1216,1221 **** --- 1216,1222 ---- if (rr <= 0) { /* at end, or fukt, or ... */ FD_CLR (0, ding1); /* disable and close stdin */ close (0); + shutdown(fd, 1); /* no more sending from us */ } else { rzleft = rr; zp = bigbuf_in; To test it: % vi /etc/inetd.conf # enable 'echo' service % nc localhost echo hello hello <CTRL-D> % Without the patch, netcat-1.10 never exits. With the patch, it exits cleanly. Thanks, Graham
This is the classic half-close problem described in Stevens and best illustrated by echo yadda yadda | rsh localhost cat (rsh needs to do shutdown(fd, 1) so that the data is returned by cat). Your fix looks like the Right Thing To Do (I have not yet looked at sources).
FIxed (by applying patch above) in nc-1.10-9. Thanks for reporting.