Chapter 4. API Guides
• select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
struct timeval *timeout) has exception descriptor indicating that the socket has an error. For more
information, see select() Errors.
Socket API Errors
The error detection
• We can know that the socket API fails according to its return value.
Get the error reason code
• When socket API fails, the return value doesn’t contain the failure reason and the application can get the
error reason code by accessing errno. Different values indicate different meanings. For more information,
see <Socket Error Reason Code>.
Example:
int err;
int sockfd;
if (sockfd = socket(AF_INET,SOCK_STREAM,0) < 0) {
// the error code is obtained from errno
err = errno;
return err;
}
select() Errors
The error detection
• Socket error when select() has exception descriptor
Get the error reason code
• If the select indicates that the socket fails, we can’t get the error reason code by accessing errno, in-
stead we should call getsockopt() to get the failure reason code. Because select() has exception
descriptor, the error code will not be given to errno.
Note: getsockopt function prototype int getsockopt(int s, int level, int optname,
void *optval, socklen_t *optlen). Its function is to get the current value of the option of any type,
any state socket, and store the result in optval. For example, when you get the error code on a socket, you can get it
by getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, &optlen).
Example:
int err;
if (select(sockfd + 1, NULL, NULL, &exfds, &tval) <= 0) {
err = errno;
return err;
} else {
if (FD_ISSET(sockfd, &exfds)) {
// select() exception set using getsockopt()
int optlen = sizeof(int);
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, &optlen);
return err;
}
}
Socket Error Reason Code Below is a list of common error codes. For more detailed list
of standard POSIX/C error codes, please see newlib errno.h <https://github.com/espressif/newlib-
esp32/blob/master/newlib/libc/include/sys/errno.h> and the platform-specific extensions
newlib/platform_include/errno.h
Espressif Systems 1426
Submit Document Feedback
Release v4.4