Alex Rivera | Logout

c++ how to use select to see if a socket has closed

Asked 2011-04-12T18:52:03.567
20

Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket?

FYI. I'm using linux.

Thanks!

Edit
Report

1 Answer

21

The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read.

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>

bool isclosed(int sock) {
  fd_set rfd;
  FD_ZERO(&rfd);
  FD_SET(sock, &rfd);
  timeval tv = { 0 };
  select(sock+1, &rfd, 0, 0, &tv);
  if (!FD_ISSET(sock, &rfd))
    return false;
  int n = 0;
  ioctl(sock, FIONREAD, &n);
  return n == 0;
}
answered 2011-04-12T18:57:24.510

Your Answer