SetSockOpt () function Introduction

Source: Internet
Author: User
Tags socket error

Function Description:

Gets or sets the options associated with a socket. Options may exist in multi-tier protocols, and they will always appear on the topmost socket layer. When you manipulate socket options, the options are located at the layer and the name of the option must be given. To manipulate the sockets Layer options, you should specify the value of the layer as sol_socket. The appropriate protocol number for the control option must be given in order to manipulate the other layer's options. For example, to indicate that an option is resolved by the TCP protocol, the layer should be set to protocol number TCP.




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 that will be set or get the option.
Level: The protocol layer where the option is located.
Optname: The name of the option that needs to be accessed.
Optval: For GetSockOpt (), point to the buffer that returns the value of the option. For setsockopt (), point to the buffer that contains the new option value.
Optlen: For GetSockOpt (), the maximum length of the option value when used as an ingress parameter. The actual length of the option value as an exit parameter. For setsockopt (), the length of the current option.




Return Description:




When executed successfully, returns 0. The failed return -1,errno is set to one of the following values
Ebadf:sock is not a valid file description word
The memory that Efault:optval points to is not a valid process space
EINVAL: Optlen Invalid when calling setsockopt ()
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock description is not a socket




Parameters Detailed Description:


level specifies the hierarchy of the control sockets. You can take three kinds of values:
1) Sol_socket: Universal socket option.
2) ipproto_ip:ip option.
3) ipproto_tcp:tcp option.
Optname Specify the mode of control (the name of the option), we explain in detail below


Optval Gets or sets the socket option. Conversion based on the data type of the option name




Option Name Description Data type
========================================================================
Sol_socket
------------------------------------------------------------------------
So_broadcast allow sending broadcast data int
So_debug Allow Debug int
So_dontroute does not find route int
So_error Getting socket error int
So_keepalive remain connected 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 bound int
So_sndlowat send buffer lower bound int
So_rcvtimeo Receive timeout struct timeval
So_sndtimeo Send timeout struct timeval
SO_REUSERADDR allow reuse of local addresses 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 in the packet
Ip_optinos IP Header option int
Ip_tos Service Type
Ip_ttl Time to live int
========================================================================
Ippro_tcp
------------------------------------------------------------------------
Tcp_maxseg the size of the TCP maximum data segment int
Tcp_nodelay does not use the Nagle algorithm int
========================================================================


Return Description:
When executed successfully, returns 0. The failed return -1,errno is set to one of the following values
Ebadf:sock is not a valid file description word
The memory that Efault:optval points to is not a valid process space
EINVAL: Optlen Invalid when calling setsockopt ()
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock description is not a socket


So_rcvbuf and So_sndbuf Each set of interfaces has a send buffer and a receive buffer, using these two sets of interface options to change the default buffer size.


Receive buffers
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));


Attention:


When setting the size of the TCP socket receive buffer, the function call order is important because the TCP window sizing option is used interchangeably with SYN when establishing the connection. For customers, the O_RCVBUF option must be set before connect, and for the server, the SO_RCVBUF option must be set before listen.


Combined with the principle description:


1. Each set of interfaces has a send buffer and a receive buffer. The receive buffer is used by TCP and UDP to persist the received data until it is read by the application process. TCP:TCP advertises the window size at the other end. The TCP socket receive buffer cannot overflow because the other party is not allowed to emit more data than the advertised window size. This is the traffic control of TCP, and if the other party ignores the window size and emits more data than the window size, the receiver TCP discards it. UDP: This datagram is discarded when the received datagram is not loaded into the socket receive buffer. UDP is no traffic control, the fast sender can easily drown the slow receiver, causing the receiver's UDP drop datagram.
2. We often hear about the three handshake of the TCP protocol, but what are the details of the three handshake, and why do we do it?
The first time: The client sends the connection request to the server, the server receives;
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 client-to-server connection.
Third time: The client returns the confirmation code of the last request sent by the server, the server receives it, and confirms the server-to-client connection.
We can see:
1. Each connection to TCP needs to be confirmed.
2. Client-to-server and server-to-client connections are independent.
Let's think about the characteristics of the TCP protocol: connected, reliable, full-duplex, and actually TCP's three-time handshake is just to ensure that these features are implemented.




Usage of 3.setsockopt


1.closesocket (typically does not close immediately and undergoes 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 you want a soket that is already in the connected state to be forced to close after calling Closesocket, do not experience the TIME_WAIT process:
BOOL Bdontlinger = FALSE;
SetSockOpt (S,sol_socket,so_dontlinger, (const char*) &bdontlinger,sizeof (BOOL));




3. In the Send (), recv () process sometimes due to network conditions and other reasons, the collection can not be expected to proceed, and set the time and delivery period:
int NNETTIMEOUT=1000;//1 sec
Delivery 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 Send (), the actual bytes sent (synchronous) or bytes sent to the socket buffer are returned.
(asynchronous); The system default state send and Receive is 8688 bytes (approximately 8.5K), and data is sent in the actual process.
and receive a large amount of data, you can set the socket buffer, and avoid the Send (), recv () Continuous loop transceiver:
Receive buffers
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 do not want to experience a copy of the system buffer to the socket buffer when sending the data
Performance of the program:
int nzero=0;
SetSockOpt (Socket,sol_s0cket,so_sndbuf, (char *) &nzero,sizeof (Nzero));




6. Complete the above function (by default, copy the contents of the socket buffer to the system buffer) in recv ():
int nzero=0;
SetSockOpt (Socket,sol_s0cket,so_rcvbuf, (char *) &nzero,sizeof (int));




7. In general, when sending a UDP datagram, you want the data sent by the socket to have broadcast characteristics:
BOOL bbroadcast=true;
SetSockOpt (S,sol_socket,so_broadcast, (const char*) &bbroadcast,sizeof (BOOL));




8. In the Client connection server process, if the socket in nonblocking mode can set the Connect () delay in the process of connect () until Accpet () is called (This function setting has a significant effect in the non-blocking process, Not very useful in blocking function calls)
BOOL bconditionalaccept=true;
SetSockOpt (s,sol_socket,so_conditional_accept, (const char*) &bconditionalaccept,sizeof (BOOL));




9. If in the process of sending the data (send () is not completed, and the data is not sent) and call Closesocket (), previously we generally take the measure is "calmly close" shutdown (S,sd_both), but the data is definitely lost, How do I set up a program that meets the requirements of a specific application (that is, after sending out data that has not been sent out and closing the socket)?
struct Linger {
U_short L_onoff;
U_short L_linger;
};
Linger M_slinger;
m_slinger.l_onoff=1;//(in the closesocket () call, but there is no data sent when the time allowed to stay)
If m_slinger.l_onoff=0, then function and 2.) function the same;
m_slinger.l_linger=5;//(allow 5 seconds to stay)
SetSockOpt (S,sol_socket,so_linger, (const char*) &m_slinger,sizeof (LINGER));

SetSockOpt () function Introduction

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.