http://www.perlmonks.org?node_id=280887


in reply to Detecting a closed socket

It depends on what you mean by "closed".

If you want to detect the case where the other end has properly disconnected, it's pretty easy: try to select on the filehandle (the 4-argument form), it will return as being ready, then an attempt to read will return eof.

If you want to include the case where the other end may have just fallen off the 'net without properly disconnecting, you have to actually write some data to the socket. TCP doesn't exchange periodic state messages, so it's impossible to tell if an absent client is disconnected or just silent. Many protocols provide NOOP-type functions for this purpose. The exception is if you use the SO_KEEPALIVE option, in which case you'll be informed of a timeout after an hour or two.

sysread shouldn't give up unless it knows there is data pending, but it receives nothing for a long time. This doesn't tend to happen in real life unless the other end really has gone away for a while (a few minutes). The details may be system dependent; you're getting into TCP/IP Illustrated territory, and I don't feel like re-reading the (verbose) details.