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

前端 未结 3 1588
遥遥无期
遥遥无期 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:08

    I agree with the accepted answer, there is no official way to determine the blocking state of a socket on Windows. In case you get a socket from a third party (let's say, you are a TLS library and you get the socket from upper layer) you cannot decide if it is in blocking state or not.

    Despite this I have a working, unofficial and limited solution for the problem which works for me for a long time.

    I attempt to read 0 bytes from the socket. In case it is a blocking socket it will return 0, in case it is a non-blocking it will return -1 and GetLastError equals WSAEWOULDBLOCK.

    int IsBlocking(SOCKET s)
    {
        int r = 0;
        unsigned char b[1];
        r = recv(s, b, 0, 0);
        if (r == 0)
            return 1;
        else if (r == -1 && GetLastError() == WSAEWOULDBLOCK)
            return 0;
        return -1; /* In  case it is a connection socket (TCP) and it is not in connected state you will get here 10060 */
    }
    

    Caveats:

    • Works with UDP sockets
    • Works with connected TCP sockets
    • Doesn't work with unconnected TCP sockets

提交回复
热议问题