Set SO_RECVBUF and SO_SENDBUF socket options, sorecvbuf
Control socket behavior (such as modifying the buffer size ).
Int getsockopt (int sockfd, int level, int optname, void * optval, socklen_t * optlen );
Int setsockopt (int sockfd, int level, int optname, const void * optval, socklen_t * optlen );
Level specifies the level of the control socket. Three values can be obtained:
Optname specifies the control method (option name)
Optval gets or sets socket options. Convert the Data Type of the Option name
Return Value description:
0 is returned when execution is successful. -1 is returned for failure, and errno is set to one of the following values
EBADF: sock is not a valid file description.
EFAULT: the memory to which optval points is not a valid process space
EINVAL: optlen is invalid when setsockopt () is called.
ENOPROTOOPT: the specified protocol layer does not recognize the option.
ENOTSOCK: sock does not describe socket
Data Structure Description:
1) structure: linger. Its declaration is as follows:
Struct linger {int l_onoff; // status int l_linger; // wait time };
2) structure: timeval. Its declaration is as follows:
Struct timeval {time_t TV _sec; // second suseconds_t TV _usec; // microsecond: one second per million };
Example:
Each interface set of SO_RCVBUF and SO_SNDBUF has a sending buffer and a receiving buffer. The default buffer size can be changed using these two Interface Options.
// Receive the buffer int nRecvBuf = 32*1024; // set it to 32 K setsockopt (s, SOL_SOCKET, SO_RCVBUF, (const char *) & nRecvBuf, sizeof (int )); // sending buffer int nSendBuf = 32*1024; // set to 32 K setsockopt (s, SOL_SOCKET, SO_SNDBUF, (const char *) & nSendBuf, sizeof (int ));
Note:
When the TCP interface is set to receive the buffer hour, the function call sequence is very important, because the TCP Window Size Option is obtained by swapping SYN with the other party when establishing a connection. For customers, the SO_RCVBUF option must be set before connect; for servers, the SO_RCVBUF option must be set before listen.