How to reset a socket back to blocking mode (after I set it to nonblocking mode)? How to reset a socket back to blocking mode (after I set it to nonblocking mode)? c c

How to reset a socket back to blocking mode (after I set it to nonblocking mode)?


Did you try clearing the O_NONBLOCK flag?

opts = opts & (~O_NONBLOCK)


Here is a more cross-platform capable solution:

bool set_blocking_mode(int socket, bool is_blocking){    bool ret = true;#ifdef WIN32    /// @note windows sockets are created in blocking mode by default    // currently on windows, there is no easy way to obtain the socket's current blocking mode since WSAIsBlocking was deprecated    u_long non_blocking = is_blocking ? 0 : 1;    ret = NO_ERROR == ioctlsocket(socket, FIONBIO, &non_blocking);#else    const int flags = fcntl(socket, F_GETFL, 0);    if ((flags & O_NONBLOCK) && !is_blocking) { info("set_blocking_mode(): socket was already in non-blocking mode"); return ret; }    if (!(flags & O_NONBLOCK) && is_blocking) { info("set_blocking_mode(): socket was already in blocking mode"); return ret; }    ret = 0 == fcntl(socket, F_SETFL, is_blocking ? flags ^ O_NONBLOCK : flags | O_NONBLOCK));#endif    return ret;}


Alternative way to clear the flag:

opts ^= O_NONBLOCK;

This will toggle the non-blocking flag, i.e. disable non-blocking if currently enabled.