Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the setsockopt and getsockopt functions under linux

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the functions of setsockopt and getsockopt under linux? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Function description:

Gets or sets the options associated with a socket. Options may exist in multilayer protocols, and they always appear in the topmost socket layer. When manipulating a socket option, the layer on which the option is located and the name of the option must be given. In order to manipulate the options of the socket layer, the value of the layer should be specified as SOL_SOCKET. In order to manipulate the options of 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.

Usage:

# include

# include

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 that will be set or get the option.

Level: the protocol layer in which the option is located.

Optname: the name of the option you need to access.

Optval: for getsockopt (), point to the buffer that returns the value of the option. For setsockopt (), point to the buffer containing the value of the new option.

Optlen: for getsockopt (), the maximum length of the option value as an entry parameter. The actual length of the option value as an exit parameter. For setsockopt (), the length of the current option.

Return description:

Returns 0 on successful execution. Failed return-1errno is set to one of the following values

EBADF:sock is not a valid file descriptor

The memory pointed to by EFAULT:optval is not a valid process space

EINVAL: optlen is not valid when calling setsockopt ()

ENOPROTOOPT: specified protocol layer does not recognize option

ENOTSOCK:sock does not describe sockets.

Details of the parameters:

Level specifies the hierarchy of control sockets. You can take three values:

1) SOL_SOCKET: universal socket option.

2) IPPROTO_IP:IP option.

3) IPPROTO_TCP:TCP option.

Optname specifies how to control (the name of the option), which we will explain in detail below

Optval gets or sets socket options. Convert according to the data type of the option name

Option name describes the data type

=

SOL_SOCKET

SO_BROADCAST allows broadcast data int to be sent

SO_DEBUG allows debugging of int

SO_DONTROUTE does not look up routing int

SO_ERROR get socket error int

SO_KEEPALIVE stay connected int

SO_LINGER delays closing connection struct linger

SO_OOBINLINE out-of-band data is put into normal data stream int

SO_RCVBUF receive buffer size int

SO_SNDBUF send buffer size int

Int, the lower limit of SO_RCVLOWAT receive buffer

Int, the lower limit of SO_SNDLOWAT send buffer

SO_RCVTIMEO receive timeout struct timeval

SO_SNDTIMEO send timeout struct timeval

SO_REUSERADDR allows reuse of local addresses and ports int

SO_TYPE gets socket type int

SO_BSDCOMPAT is compatible with BSD system and int

=

IPPROTO_IP

IP_HDRINCL contains the IP header int in the packet

IP_OPTINOSIP first option int

IP_TOS service type

IP_TTL time to Live int

=

IPPRO_TCP

The size int of the most big data segment of TCP_MAXSEGTCP

TCP_NODELAY does not use Nagle algorithm int

=

Return description:

Returns 0 on successful execution. Failed return-1errno is set to one of the following values

EBADF:sock is not a valid file descriptor

The memory pointed to by EFAULT:optval is not a valid process space

EINVAL: optlen is not valid when calling setsockopt ()

ENOPROTOOPT: specified protocol layer does not recognize option

ENOTSOCK:sock does not describe sockets.

SO_RCVBUF and SO_SNDBUF each socket has a send buffer and a receive buffer, and you can use these two socket options to change the default buffer size.

/ / receive buffer

Int nRecvBuf=32*1024; / / set to 32K

Setsockopt (const char*) & nRecvBuf,sizeof (int))

/ / send buffer

Int nSendBuf=32*1024;// is set to 32K

Setsockopt (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 window size option of TCP is interchanged with each other with SYN when establishing a connection. For customers, the O_RCVBUF option must be set before connect; for servers, the SO_RCVBUF option must be set before listen.

Combined with the principle to explain:

1. Each socket has a send buffer and a receive buffer. The receive buffer is used by TCP and UDP to save the received data until read by the application process. TCP:TCP advertises the size of the window at the other end. The TCP socket receive buffer cannot overflow because the other party is not allowed to emit data that exceeds the size of the advertised window. This is the flow control of TCP, and if the other party sends data that exceeds the window size regardless of the window size, the receiver TCP will discard it. UDP: when the received Datagram is not loaded into the socket receive buffer, the Datagram is discarded. UDP has no flow control; a fast sender can easily drown a slow receiver, causing the receiver's UDP to discard datagrams.

two。 We often hear about the three-way handshake in the tcp protocol, but what exactly is the three-way handshake, what are the details, and why do you do it?

The first time: the client sends a connection request to the server and the server receives

The second time: the server returns a confirmation code to the client with a connection request from the server to the client, and 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, and the server receives and confirms the connection between the server and the client.

We can see:

1. Each connection to tcp needs to be confirmed.

two。 Client-to-server and server-to-client connections are independent.

Let's consider the characteristics of tcp protocol: connected, reliable, full-duplex. In fact, tcp's three-way handshake is to ensure the implementation of these features.

The usage of 3.setsockopt

1.closesocket (usually does not close immediately but goes through the process of TIME_WAIT) and wants to continue to reuse the socket:

BOOL bReuseaddr=TRUE

Setsockopt (SO_REUSEADDR, const char*) & bReuseaddr,sizeof (BOOL))

two。 If you want the soket that is already in the connected state to be forced to close after calling closesocket, you will not go through the process of TIME_WAIT:

BOOL bDontLinger = FALSE

Setsockopt (const char*) & bDontLinger,sizeof (BOOL))

3. In the process of send () and 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

/ / sending time limit

Setsockopt (socket,SOL_S0CKET,SO_SNDTIMEO, (char *) & nNetTimeout,sizeof (int))

/ / receiving time limit

Setsockopt (socket,SOL_S0CKET,SO_RCVTIMEO, (char *) & nNetTimeout,sizeof (int))

4. In the case of send (), the bytes actually sent (synchronized) or sent to the socket buffer are returned

(asynchronous); the default state of the system is to send and receive 8688 bytes at a time (about 8.5K); send data in the actual process

And the amount of data received is relatively large, so you can set the socket buffer to avoid the continuous cyclic sending and receiving of send () and recv ():

/ / receive buffer

Int nRecvBuf=32*1024;// is set to 32K

Setsockopt (const char*) & nRecvBuf,sizeof (int))

/ / send buffer

Int nSendBuf=32*1024;// is set to 32K

Setsockopt (const char*) & nSendBuf,sizeof (int))

5. If you want not to experience a copy from the system buffer to the socket buffer when sending data

Performance of the program

Int nZero=0

Setsockopt (socket,SOL_S0CKET,SO_SNDBUF, (char *) & nZero,sizeof (nZero))

6. Do the above in recv () above (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 a UDP Datagram, you want the data sent by the socket to have broadcast characteristics:

BOOL bBroadcast=TRUE

Setsockopt (const char*) & bBroadcast,sizeof (BOOL))

8. In the process of client connecting to the server, if socket in non-blocking mode can set connect () delay in the process of connect () until accpet () is called (this function setting only plays a significant role in non-blocking process, but not in blocking function calls)

BOOL bConditionalAccept=TRUE

Setsockopt ((const char*) & bConditionalAccept,sizeof (BOOL))

9. If in the process of sending data (send () did not complete, there is no data sent) and called closesocket (), before we generally take the measure is to "calmly close" shutdown (sforce SDendBOTH), but the data is definitely lost, how to set so that the program to meet the requirements of specific applications (that is, to let the unfinished data sent out after closing socket)?

Struct linger {

U_short l_onoff

U_short l_linger

}

Linger m_sLinger

In closesocket () call, but there is still time to stay when the data is not sent.

/ / if mroomsLinger.lactionoffsetting 0; then the function and 2.) The effect is the same

Makeshift Linger.lingerbread 5 (5 seconds allowed to stay)

Setsockopt, (const char*) & MirrsLinger (linger))

After reading the above, have you mastered what the setsockopt and getsockopt functions are under linux? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report