Is it safe to pass recv to 0 to detect socket errors?

Is it safe to call for a TCP blocking socket:

if(SOCKET_ERROR != recv(s, NULL, 0, 0))
//...

to detect errors?

I thought it was safe, then I had a situation on the computer that hung on this statement. (was with ssl socket, if that matters). I also tried passing the MSG_PEEK flag with the specified buffer, but I also hung myself there.

Which alternative?

+3
source share
3 answers

In addition to the other answers, here is a small handy feature for getting a pending socket error:


/* Retrives pending socket error. */
int get_socket_error( int sockfd )
{
    int error;
    socklen_t len( sizeof( error ));

    if ( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) < 0 )
        error = errno;

    return error;
}
+4
source

, , select ( select). , , .

+3

The call itself is “safe” in the sense that it should work as documented , however, you must understand what recvis blocking the reception of the call. This means that the call blocks the executable thread until data arrives at the socket. This can cause the application to freeze if you do not use another thread to receive it or check if data is available before receiving a call ( select ).

+2
source

Source: https://habr.com/ru/post/1712189/


All Articles