In Win32, is there a way to test if a socket is non-blocking?

前端 未结 3 1585
遥遥无期
遥遥无期 2020-12-06 06:48

In Win32, is there a way to test if a socket is non-blocking?

Under POSIX systems, I\'d do something like the following:

int is_non_blocking(int sock         


        
3条回答
  •  独厮守ぢ
    2020-12-06 07:15

    Previously, you could call WSAIsBlocking to determine this. If you are managing legacy code, this may still be an option.

    Otherwise, you could write a simple abstraction layer over the socket API. Since all sockets are blocking by default, you could maintain an internal flag and force all socket ops through your API so you always know the state.

    Here is a cross-platform snippet to set/get the blocking mode, although it doesn't do exactly what you want:

    /// @author Stephen Dunn
    /// @date 10/12/15
    bool set_blocking_mode(const 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 flags = is_blocking ? 0 : 1;
        ret = NO_ERROR == ioctlsocket(socket, FIONBIO, &flags);
    #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;
    }
    

提交回复
热议问题