The only other option is if it is TCP is to have TCP send a keep-alive every so often, which is still polling such as what you're doing now but handled at the TCP layer so you're protocol doesn't need to know.
There's no way around the polling however since without sending something to the other client and getting a response you have no way to know whether it's still connected or not.
Keep alive may also be required anyway when communicating through stateful packet inspection such as standard NAPT to avoid having the remote server drop the session due to in-activity.
On macOS Big Sur
and later, use this command:
sudo lsof -i -P | grep LISTEN
or to just see just IPv4:
sudo lsof -nP -i4TCP:$PORT | grep LISTEN
On older versions, use one of the following forms:
sudo lsof -nP -iTCP:$PORT | grep LISTEN
sudo lsof -nP -i:$PORT | grep LISTEN
Substitute $PORT
with the port number or a comma-separated list of port numbers.
Prepend sudo
(followed by a space) if you need information on ports below #1024.
The -n
flag is for displaying IP addresses instead of host names. This makes the command execute much faster, because DNS lookups to get the host names can be slow (several seconds or a minute for many hosts).
The -P
flag is for displaying raw port numbers instead of resolved names like http
, ftp
or more esoteric service names like dpserve
, socalia
.
See the comments for more options.
For completeness, because frequently used together:
To kill the PID:
sudo kill -9 <PID>
# kill -9 60401
Best Answer
In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from
read()/recv()/recvXXX()
when reading.There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and timeouts to know that it's broken and will eventually cause
write()/send()/sendXXX()
to return -1 with anerrno/WSAGetLastError()
value ofECONNRESET,
or in some cases 'connection timed out'. Note that the latter is different from 'connect timeout', which can occur in the connect phase.You should also set a reasonable read timeout, and drop connections that fail it.
The answer here about
ioctl()
andFIONREAD
is compete nonsense. All that does is tell you how many bytes are presently in the socket receive buffer, available to be read without blocking. If a client doesn't send you anything for five minutes that doesn't constitute a disconnect, but it does causeFIONREAD
to be zero. Not the same thing: not even close.