Summary of getsockopt and setsockopt in Linux

Source: Internet
Author: User

Function Description:

Gets or sets the options associated with a socket. Options may exist in multi-layer protocols, and they will always appear at the top socket layer. When you operate on socket options, the layer at which the options are located and the name of the options must be provided. To operate the socket layer options, specify the layer value as sol_socket. In order to operate on the options of other layers, the appropriate Protocol Number of the control options 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 for which the options will be set or obtained.

Level: the protocol layer of the option.

Optname: name of the option to be accessed.

Optval: For getsockopt (), the buffer pointing to the returned option value. For setsockopt (), point to the buffer containing the new option value.

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

Return 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

Parameter Details:

Level specifies the level of the control socket. Three values can be obtained:

1) sol_socket: General socket options.

2) ipproto_ip: IP Option.

3) ipproto_tcp: TCP option.

Optname specifies the control method (option name), which is explained in detail below

Optval gets or sets socket options. Convert the Data Type of the Option name

Option Name Description Data Type

========================================================== ======================================

Sol_socket

------------------------------------------------------------------------

So_broadcast allows sending broadcast data int

So_debug allows int debugging

So_dontroute

So_error get socket error int

So_keepalive

So_linger delay disconnection struct linger

So_oobinline put out-of-band data into normal data stream int

So_rcvbuf receive buffer size int

So_sndbuf sending buffer size int

So_rcvlowat lower limit int of the receiving buffer

So_sndlowat lower limit int of the sending Buffer

So_rcvtimeo receiving timeout struct timeval

So_sndtimeo sending timeout struct timeval

So_reuseraddr allows reuse of the local address and port int

So_type: Obtain the socket type Int.

So_bsdcompat is compatible with the BSD system int

========================================================== ======================================

Ipproto_ip

------------------------------------------------------------------------

Ip_hdrincl contains the IP header int in the data package.

Ip_optinosip header option int

Ip_tos service type

Ip_ttl time int

========================================================== ======================================

Ippro_tcp

------------------------------------------------------------------------

Tcp_maxsegtcp maximum data segment size int

Tcp_nodelay does not use the Nagle algorithm int

========================================================== ======================================

Return 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

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.

// Receiving 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 it 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 o_rcvbuf option must be set before connect; for servers, the so_rcvbuf option must be set before listen.

Principles:

1. Each set of interfaces has a sending buffer and a receiving buffer. The receiving buffer is used by TCP and UDP to keep the received data for read by the application process. TCP: The window size of TCP advertised to the other end. The receiving buffer of the TCP interface cannot overflow, because the other party cannot send data that exceeds the size of the advertised window. This is TCP traffic control. If the recipient ignores the window size and sends out data that exceeds the window size, the receiver TCP discards the data. UDP: When the received data report is not included in the interface to receive the buffer, the datagram is discarded. There is no traffic control for UDP. A fast sender can easily drown out slow recipients, causing the receiver to discard the UDP datagram.

2. We often hear about the three-way handshake of TCP, but what is the three-way handshake, what is its details, and why?

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 the request and confirms the connection from the client to the server.

Third time: the client returns the confirmation code sent by the server last time. The server receives the confirmation code and confirms the connection from the server to the client.

We can see that:

1. Confirm each TCP connection.

2. The client-to-server and server-to-client connections are independent.

Let's look at the features of TCP: connection, reliability, and full duplex. In fact, TCP's three-way handshake is designed to ensure the implementation of these features.

3. setsockopt usage

1. closesocket (usually does not close immediately and goes through the time_wait process) 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 in the connection state needs to be forcibly closed after closesocket is called, it does not go through the time_wait process:

Bool bdontlinger = false;

Setsockopt (S, sol_socket, so_dontlinger, (const char *) & bdontlinger, sizeof (bool ));

3. In the send () and Recv () processes, sometimes due to network conditions and other reasons, sending and receiving cannot be performed as expected, but set the sending and receiving time limit:

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. When sending (), the returned bytes are actually sent (synchronized) or the bytes sent to the socket buffer.

(Asynchronous); by default, the system sends and receives data in 8688 bytes (about 8.5 KB) at a time.

When receiving a large amount of data, you can set a socket buffer to avoid the continuous cyclic sending and receiving of send () and Recv:

// Receiving 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 it to 32 K

Setsockopt (S, sol_socket, so_sndbuf, (const char *) & nsendbuf, sizeof (INT ));

5. If you want to avoid the impact of copying data from the system buffer to the socket buffer when sending data

Program performance:

Int nzero = 0;

Setsockopt (socket, sol_s0cket, so_sndbuf, (char *) & nzero, sizeof (nzero ));

6. Complete the preceding functions in Recv (). By default, the socket buffer content is copied 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 the broadcast feature:

Bool bbroadcast = true;

Setsockopt (S, sol_socket, so_broadcast, (const char *) & bbroadcast, sizeof (bool ));

8. when the client connects to the server, if the socket in non-blocking mode is in the connect () process, you can set the connect () delay until accpet () called (this function setting only plays a significant role in the non-blocking process, but does not play a major role in blocked function calls)

Bool bconditionalaccept = true;

Setsockopt (S, sol_socket, so_conditional_accept, (const char *) & bconditionalaccept, sizeof (bool ));

9. if closesocket () is called while sending data (sending () is not completed and data is not sent (), in the past, we used to take the "Easy to close" Shutdown (S, sd_both), but the data is definitely lost, how can I set a program to meet the requirements of a specific application (that is, to disable socket after sending unsent data )?

Struct linger {

U_short l_onoff;

U_short l_linger;

};

Linger m_slinger;

M_slinger.l_onoff = 1; // (allowed to stay when closesocket () is called, but there is still data not sent)

// If m_slinger.l_onoff = 0, the function is the same as 2;

M_slinger.l_linger = 5; // (the allowable stay time is 5 seconds)

Setsockopt (S, sol_socket, so_linger, (const char *) & m_slinger, sizeof (linger ));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.