Get and set socket options

    The following methods can be used to get and set options that affect sockets:
    (1) getsockopt and setsockopt functions;
    (2) fcntl function;
    (3) ioctl function.
    This article will introduce the getsockopt and setsockopt functions. For the introduction of fcntl, see the introduction of fcntl function , and the introduction of ioctl is reserved for later.
#include <sys/socket.h>
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);
                              /* The return value of the two functions: if successful, return 0; otherwise, return -1 */

    Where the parameter sockfd points to an open socket descriptor, and level specifies the code in the system that interprets the option, either a generic socket code, or a protocol-specific code such as IPv4, IPv6, TCP, or SCTP. optval is a pointer to a variable, setsockopt obtains the new value of the option optname to be set from *optval, and getsockopt stores the obtained current value of the option optname into *optval. The size of *optval is specified by the optlen parameter.
    Socket options are roughly divided into two basic types: binary options that enable or disable a feature (called flag options), and options that take and return specific values ​​that can be set or checked (called value options) ). The following two tables summarize the options that can be obtained and set by getsockopt and setsockopt. The "Data Type" column gives the data type of each option that the pointer optval must point to (the notation followed by a pair of curly braces in this column indicates a structure, such as linger{} means struct linger), marked with " The column of "flags" indicates whether an option is a flag option. When the value of *optval is 0, it means the option is disabled, otherwise it means it is enabled. If the "Flags" column does not contain "·", then the corresponding option is used to pass the value of the specified data type between the user process and the system.


    Several of these socket options are inherited by TCP connected sockets from listening sockets: SO_DEBUG, SO_DONTROUTE, SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE, SO_RCVBUF, SO_RCVLOWAT, SO_SNDBUF, SO_SNDLOWAT, TCP_MAXSEG, and TCP_NODELAY. This is important for TCP because accept does not return a connected socket to the server until the TCP layer completes the three-way handshake. If you want to ensure that one of these socket options is set for the connected socket when the three-way handshake is complete, you must first set that option for the listening socket.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326197478&siteId=291194637