Getting error number returned by recv function

8.8k Views Asked by At

How can I get the error number or error string returned by the recv() in socket communication, recv() returns -1 as read size which means some error has occurred. I want to know the specific reason for the error. so how can I get that.

2

There are 2 best solutions below

4
Iharob Al Asimi On BEST ANSWER

You need to include errno.h and use the errno global variable to check the last error code. Also, you can use strerror() to print a locale aware string explaining the error.

Example

#include <errno.h>

ssize_t size;

if ((size = recv( ... )) == -1)
{
    fprintf(stderr, "recv: %s (%d)\n", strerror(errno), errno);
}
0
Sourav Ghosh On

You can make use of the errno variable from errno.h header file.

From the man page (emphasis mine)

Return Value

Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

Alternatively, you can also call perror() / strerror() to get a human-readable string related to the error.