Checking if a socket is closed on the other side
Published by packi on
Updated by packi on

Today I had to code something up that checks if a socket got closed on the other end, without touching the data if it’s still up and running. I came up with the following lines:

  bool isSocketAlive(const int _socketHandle) {
    uint8_t tmp;
    bool result = true;
    int res = recv(_socketHandle, &tmp, 1,  MSG_PEEK | MSG_DONTWAIT);
    if(res == -1) {
      if((errno != EAGAIN) && (errno != EINTR) && (errno != EWOULDBLOCK)) {
        log("lost connection", lsInfo);
        result = false;
      }
    } else if(res == 0) {
      // if we were still connected, recv would return -1 with an errno listed above or 1
      log("lost connection", lsInfo);
      result = false;
    }
    return result;
  } // isSocketAlive