Search code examples
clinuxreturn-valueerrnostrerror

Getting error number returned by recv function


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.


Solution

  • 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);
    }