Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe to recv passing in 0 to detect a socket error?

Tags:

c++

sockets

For a TCP blocking socket, is it safe to call:

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

to detect errors?

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

What is the alternative?

like image 213
Net Citizen Avatar asked Jan 19 '26 09:01

Net Citizen


1 Answers

In addition to other answers - here's a handy little function to get the 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;
}
like image 83
Nikolai Fetissov Avatar answered Jan 21 '26 21:01

Nikolai Fetissov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!