socket details setsockopt

1. Function description: Get or set options associated with a socket. Options may exist in multiple layers of protocols, and they will always appear at the top socket layer. When manipulating socket options, the layer at which the option is located and the name of the option must be given. In order to manipulate socket layer options, the value of the layer should be specified as SOL_SOCKET. In order to manipulate options at other layers, the appropriate protocol number for the control option must be given. For example, to indicate that an option is parsed by the TCP protocol, the layer should be set to the protocol number TCP.  

2. Specific usage:
#include <sys/types.h>
#include <sys/socket.h>

int getsockopt(int sock, int level, int optname, void *optval, socklen_t *optlen);

int setsockopt(int sock, int level, int optname, const void *optval, socklen_t optlen);

Parameters:  
sock: The socket on which the option will be set or obtained.
level: The protocol layer where the option is located.
optname: The option name to be accessed.
optval: For getsockopt(), points to the buffer that returns the option value. For setsockopt(), points to a buffer containing the new option value.
optlen: For getsockopt(), when used as an entry parameter, the maximum length of the option value. The actual length of the option value when used as an exit parameter. For setsockopt(), the length of the current option.

Return description:  
When executed successfully, return 0. On failure -1 is returned, errno is set to one of the following values  
​​EBADF: sock is not a valid file descriptor
EFAULT: memory pointed to by optval is not valid process space
EINVAL: optlen is invalid when calling setsockopt()
ENOPROTOOPT: specified protocollayer does not recognize the option
ENOTSOCK: sock describes not a socket

parameter Details:
level specifies the level of control sockets. It can take three values:
1) SOL_SOCKET: general socket option.
2) IPPROTO_IP: IP option.
3) IPPROTO_TCP: TCP option.
 


optname specifies the control method (the name of the option), we explain in detail below that 

optval obtains or sets socket options. Conversion is performed according to the data type of the option name. The 


option name indicates the data type
=========== ===================================================== ==========
            SOL_SOCKET
--------------------------------------- ---------------------------------
SO_BROADCAST allow sending broadcast data int
SO_DEBUG allow debugging int
SO_DONTROUTE do not look for routes int
SO_ERROR get socket error int
SO_KEEPALIVE keep connection int
SO_LINGER delay closing connection struct linger
SO_OOBINLINE out-of-band data into normal data stream int
SO_RCVBUF receive buffer size int
SO_SNDBUF send buffer size int
SO_RCVLOWAT receive buffer lower limit int
SO_SNDLOWAT send buffer lower limit int
SO_RCVTIMEO receive timeout struct timeval
SO_SNDTIMEO send timeout struct timeval
SO_REUSERADDR allow reuse of local address and port int
SO_TYPE get socket type int
SO_BSDCOMPAT compatible with BSD systems int
======= ===================================================== ==============
            IPPROTO_IP
---------------------------------- -------------------------------------- IP_HDRINCL contains the IP header int IP_OPTINOS IP header
in the packet
options int
IP_TOS type of service
IP_TTL time to live int
===================================================== =======================
            IPPRO_TCP
--------------------------------------- ---------------------------------------------
TCP_MAXSEG TCP maximum segment The size of int
TCP_NODELAY does not use Nagle's algorithm int
=========================================== ==============================

Return Description:  
Returns 0 when executed successfully. On failure -1 is returned, errno is set to one of the following values  
​​EBADF: sock is not a valid file descriptor
EFAULT: memory pointed to by optval is not valid process space
EINVAL: optlen is invalid when calling setsockopt()
ENOPROTOOPT: specified protocol The layer does not recognize the option
ENOTSOCK: sock does not describe a socket

About SO_RCVBUF and SO_SNDBUF
SO_RCVBUF and SO_SNDBUF Each socket has a send buffer and a receive buffer, using these two socket options can 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));

//send buffer
int nSendBuf=32*1024;//set to 32K
setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof(int));

Note:
        When setting the size of the TCP socket receive buffer, the order of function calls is important, because the TCP window size option is It is obtained by exchanging SYN with the other party when establishing a connection. For clients, the O_RCVBUF option must be set before connect; for servers, the SO_RCVBUF option must be set before listen.


3. Combining principle description:

        1. Each socket has a sending buffer and a receiving buffer. The receive buffer is used by TCP and UDP to keep the received data until it is read by the application process. TCP: TCP advertises the window size of the other side. The TCP socket receive buffer cannot overflow because the other party is not allowed to send more data than the advertised window size. This is TCP's flow control, if the other party sends out data that exceeds the window size regardless of the window size, the receiver TCP will discard it. UDP: When the received datagram does not fit into the socket receive buffer, the datagram is discarded. UDP has no flow control; a fast sender can easily overwhelm a slow receiver, causing the receiver's UDP to drop datagrams.
        2. We often hear about the three-way handshake of the tcp protocol, but what exactly is the three-way handshake, what are its details, and why do we do it?
        The first time: the client sends a connection request to the server, and the server receives it;
        The second time: the server returns a confirmation code to the client, with a connection request from the server to the client, the client receives and confirms the connection from the client to the server.
        The third time: the client returns the confirmation code of the last request sent by the server , the server receives, confirms the connection from the server to the client.
        We can see:
        (1) Each connection of tcp needs to be confirmed.
        (2) The connection of client to server and server to client is independent.
        Let's think about tcp again The characteristics of the protocol: connected, reliable, full-duplex, in fact, the three-way handshake of tcp is to ensure the realization of these characteristics.

4. Usage of

setsockopt 1. Close socket (generally not closed immediately and go through the process of TIME_WAIT) and want to continue to reuse the socket:
BOOL bReuseaddr=TRUE;
setsockopt(s,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL ));

2. If the soket that is already connected is forcibly closed after calling closesocket without going through the process of TIME_WAIT:
BOOL bDontLinger = FALSE;
setsockopt(s,SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL) );

3. In the process of send(), recv(), sometimes due to network conditions and other reasons, the sending and receiving cannot be expected, and the sending and receiving time limit is set:
int nNetTimeout=1000;//1 second
//The sending time limit
setsockopt(socket, SOL_S0CKET ,SO_SNDTIMEO,(char *)&nNetTimeout,sizeof(int));
//Receive time limit
setsockopt(socket,SOL_S0CKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));

4. When send(), return It is the bytes actually sent out (synchronous) or the bytes sent to the socket buffer
(asynchronous); the default state of the system to send and receive once is 8688 bytes (about 8.5K); data is sent in the actual process
If the amount of received data is relatively large, the socket buffer can be set to avoid the continuous cyclic sending and receiving of send() and recv():
// Receive buffer
int nRecvBuf=32*1024;//Set to 32K
setsockopt(s,SOL_SOCKET ,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int));
//Send buffer
int nSendBuf=32*1024;//Set to 32K
setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof( int));

5. If you want to not affect the performance of the program by copying the system buffer to the socket buffer when sending data
:
int nZero=0;
setsockopt(socket, SOL_S0CKET, SO_SNDBUF, (char *)&nZero ,sizeof(nZero));

6. Same as above in recv() to complete the above function (the default is to copy the contents of the socket buffer to the system buffer):
int nZero=0;
setsockopt(socket, SOL_S0CKET, SO_RCVBUF, (char * )&nZero,sizeof(int));

7. Generally, when sending UDP datagrams, it is hoped that the data sent by the socket has broadcast characteristics:
BOOL bBroadcast=TRUE;
setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char*)&bBroadcast,sizeof(BOOL));

8. During the process of connecting the client to the server, if the socket in non-blocking mode is in the process of connect(), you can set connect() Delay until accept() is called (this function setting has a significant effect only in the non-blocking process, and has little effect in the blocking function call)
BOOL bConditionalAccept=TRUE;
setsockopt(s,SOL_SOCKET,SO_CONDITIONAL_ACCEPT,(const char*)&bConditionalAccept,sizeof(BOOL));

9. If closesocket() is called during the process of sending data (send() has not been completed, and data has not been sent), the usual measure we used before was "Close with ease" "shutdown(s, SD_BOTH), but the data is definitely lost, how to set the program to meet the requirements of the specific application (that is, to close the socket after the unfinished data is sent out)?
struct linger {
u_short l_onoff;
u_short l_linger;
};
linger m_sLinger;
m_sLinger.l_onoff=1;//(It is allowed to stay when closesocket() is called, but there is still data to be sent)
// if m_sLinger.l_onoff=0; Then the function is the same as 2.);
m_sLinger.l_linger=5;//(The time allowed to stay is 5 seconds)
setsockopt(s,SOL_SOCKET,SO_LINGER,(const char*)&m_sLinger,sizeof(linger));

Guess you like

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