Sometimes we need to control the behavior of sockets (such as changing the size of the buffer), and we're going to learn the socket options.
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 hierarchy of the control sockets. You can take three values:
Sol_socket: Universal socket option.
IPPROTO_IP:IP option.
IPPROTO_TCP:TCP option.
OPTNAME Specifies the control (name of the option)
Optval Gets or sets the socket option. Conversion based on the data type of the option name
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/
Return Value Description:
When successfully executed, returns 0. Failure returns -1,errno is set to one of the following values
Ebadf:sock is not a valid file descriptive word
Efault:optval point to memory is not a valid process space
Einval: Optlen is not valid when setsockopt () is invoked
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock is not describing a socket
Data structure Description:
1) Structure: Linger, its declaration is as follows:
struct linger{
int l_onoff; State
int L_linger; Wait Time
};
2) Structure: Timeval, its declaration is as follows:
struct timeval{
time_t tv_sec; Seconds
suseconds_t tv_usec/microsecond: One out of 10,000 sec
};
An example is provided:
So_rcvbuf and So_sndbuf Each set of interfaces have a send buffer and a receive buffer, using these two sets of interface options to change the default buffer size.
Receive buffer
int nrecvbuf=32*1024; Set to 32K
setsockopt (s,sol_socket,so_rcvbuf, (const char*) &nrecvbuf,sizeof (int));
The send buffer
int nsendbuf=32*1024;//is set to 32K
setsockopt (s,sol_socket,so_sndbuf, (const char*) &nsendbuf, sizeof (int));
Attention:
The order of function calls is important when setting the size of the TCP socket receive buffer, because the TCP window sizing option is exchanged with SYN to the other side when establishing the connection. For customers, the SO_RCVBUF option must be set before connect, and for the server, the SO_RCVBUF option must be set before listen.