SetSockOpt usage Explanation

Source: Internet
Author: User

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 process of time_wait:
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.InSend (), return the actual bytes sent out(Synchronous) or Send Tobytes of the socket buffer
(asynchronous 8688 bytes (about 8.5k) In the actual process of sending data
and receive a large amount of data, you can set The socket buffer, avoiding the send (), recv () continuous cyclic transceiver: The
//  receive buffer
Int nrecvbuf=32*1024;//is 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 send data without experiencing a copy of the system buffer to the
Program performance:
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 non-blocking mode is in the process of connect (), you can
To set the connect () delay until accpet () is called (this function is set only in the non-blocking process with significant
function, which has little effect in blocking functions )
BOOL bconditionalaccept=true;
setsockopt (S,sol_socket,so_conditional_accept, (const char*) &bconditionalaccept,sizeof (BOOL));


9If you are in the process of sending data(Send () is not finished, and data is not sent) and call theClosesocket (), previously we
The measures generally taken are"Calmly close "shutdown (S,sd_both), but the data is definitely lost, how to set the program to meet the specific
Application requirements socket"?
struct Linger {
U_short l_onoff;
U_short L_linger;
};
Linger M_slinger;
m_slinger.l_onoff=1;//(in closesocket () call )
//  if the Span lang= "en-us" xml:lang= "en-US" >m_slinger.l_onoff=0, then features and 2.) function the same m_slinger.l_linger=5;//(allowable stay is 5 seconds setsockopt (S,sol_socket,so_linger, (const char*) &m_slinger,sizeof (LINGER));

so_linger 

    This option specifies how close the function is to the connection-oriented protocol (for example, TCP). The default close operation returns immediately, and if there is data remaining in the socket buffer, the system will try to send the data to the other side.   the


So_linger option is used to change this default setting. Use the following structure:  

struct Linger { 

     int l_onoff;  

      int L_linger;  

}; 


has the following three cases:  

L_onoff is 0, the option is off, L_linger value is ignored, equals default, close returns;  immediately

L_onoff is a non-0,l_linger of 0, then TCP terminates the connection when the socket is closed, TCP discards any data left in the socket send buffer and sends an RST to the other, rather than the usual four packet termination sequence, which avoids the time_wait state; &NBSP

L_onoff is non-0,l_linger and the kernel will delay for a period of time (determined by L_linger) when the set interface is closed. If the data is still left in the socket buffer, the process is asleep until (a) all data is sent and confirmed by the other, followed by a normal termination sequence (the descriptive Word access count is 0) or (b) the delay time. In this case, it is important for the application to check the return value of close, and close will return a ewouldblock error and any data in the socket send buffer is lost if the data is sent and confirmed before the time is reached. The successful return of close only tells us that the data sent (and Fin) has been confirmed by the other TCP, and it does not tell us if the application process has read the data. If the set interface is set to non-blocking, it will not wait for close to complete.  


L_linger is dependent on the implementation, and 4.4BSD assumes that the unit is a clock tick (1% seconds), but the posix.1g is specified in seconds.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////

Sets the options for the socket interface.

#include <winsock.h>

int PASCAL Farsetsockopt(SOCKET s, int level, int optname,
const char far* optval, int optlen);

S: A descriptive word that identifies a set of interfaces.
Level: The hierarchy of option definitions; currently only supportedSol_socket andIPPROTO_TCP level.
Optname: Options to be set.
Optval: Pointer to the buffer that holds the option value.
Optlen:The length of the optval buffer.

Comments:
setsockopt() function is used for setting option values of any type, any state socket interface. Although there are options on different protocol tiers, this function only defines the highest"Socket interface"Options on the hierarchy. Options affect the operation of the socket, such as whether the expedited data is received in the normal data stream, whether the broadcast data can be sent from the socket, and so on.
There are two options for the set of interfaces: One is a Boolean option that allows or disables one, and the other is the shaping or structure option. Allows a boolean option, theOptval points to non-0 shaping numbers; Disable an optionOptval points to an integer equal to zero. For Boolean options,Optlen should be equal tosizeof (int); For other options,Optval points to the number of shapes or structures that contain the options you want, andThe Optlen is the length of the shaping number or structure.The So_linger option is used to control actions that have queued pending data on the socket interface, andThe closesocket () call has been executed. SeeThe Closesocket () function is aboutThe So_linger option pairsThe effect of closesocket () semantics. Application by creating aLinger structure to set the corresponding operating characteristics:
struct Linger {
int L_onoff;
int L_linger;
};
To allowSo_linger, the application shouldL_onoff is set to non-zero, theL_linger is set to zero or the time-out value (in seconds) that is required, and then calls thesetsockopt()。 To allowSo_dontlinger (i.e. prohibitedSo_linger),The L_onoff should be set to zero and then calledsetsockopt()。
By default, a set of interfaces cannot be bundled with a local address that is already in use (seeBind ()). But sometimes it takesThe ReuseAddress Because each connection is uniquely determined by the combination of the local address and the remote address, it is not a big deal to bundle two sets of interfaces with one address as long as the remote address is different. In order to informWindows nested interface implementations do not allow an address to be bundled with another set of interfaces because it is used by a single socket, and the application canBind () before the call is setSO_REUSEADDR option. Please note that only theThis option is only interpreted when bind () is called, so it is not necessary (but harmless) to set this option for a socket that does not share the address, orBind () Sets or clears this option without affecting this or any other set of interfaces.
An application can be opened by openingThe So_keepalive option allowsThe Windows nested interface implementationAllow using in TCP connection casesThe Keep activePackage OneWindows nested interface implementations are not required to supportThe Keep active", but if supported, the specific semantics will be related to implementation and should be subject toRFC1122 "Internet host requirements-communication layer"In partSpecification of the 4.2.3.6 section. If the connection is due toThe Keep active, any calls to that socket in progress will beThe Wsaenetreset error is returned, and any subsequent calls will beWsaenotconn error returned.
The Tcp_nodelay option prohibitsNagle algorithm.The Nagle algorithm reduces the number of fragmented small packets sent by the host by storing unacknowledged data in buffers until a package is sent together. But for some applications, this algorithm will degrade system performance. SoTcp_nodelay can be used to turn this algorithm off. The application writer only sets the correct understanding of its effect and does need it.Tcp_nodelay option because it has a significant negative impact on network performance after setup.Tcp_nodelay is the only useIPPROTO_TCP layer options, all other options are usedSol_socket layer.
If you set theSo_debug options,The Windows Sockets vendor is encouraged (but not required) to provide the appropriate debugging information for the output. However, the mechanism of generating debugging information and the form of debugging information are beyond the scope of this specification.
setsockopt() supports the following options. which"Type"indicatesThe type of data that the optval refers to.
OptionsTypeSignificance
The So_broadcast BOOL allows the socket interface to transmit broadcast information.
So_debug BOOL Records debug information.
So_dontliner BOOL do not block the shutdown operation because the data is not sent. Setting this option is equivalent toSo_linger'sThe L_onoff element is zeroed.
So_dontroute BOOL is forbidden to select the path, direct transmission.
So_keepalive BOOL SendThe Keep activePackage
So_linger struct LINGER far* If there is no data sent when closed, then stay.
So_oobinline BOOL receives out-of-band data in the regular data stream.
The so_rcvbuf int determines the buffer size for the receive.
The SO_REUSEADDR BOOL allows the socket interface to be bundled with an address that is already in use (seeBind ()).
SO_SNDBUF int Specifies the send buffer size.
Tcp_nodelay BOOL prohibit sending of mergedNagle algorithm.

setsockopt() not supportedBSD options are:
Option nameTypeSignificance
So_acceptconn BOOL socket interface is being monitored.
So_error int gets the error state and clears.
So_rcvlowat Int receives a low-level watermark.
So_rcvtimeo int receive timeout.
So_sndlowat int sends a low-level watermark.
So_sndtimeo int send timeout.
So_type int sets the interface type.
Ip_options inSet options in the IP header.

return value:
If no error occurs,setsockopt() returns0. Otherwise, returnSocket_error error, the application can pass theWSAGetLastError () Gets the appropriate error code.

Error code:
Wsanotinitialised: When using thisAPI should first be successfully called prior to theWSAStartup ().
Wsaenetdown:The Windows nested interface implementation detects network sub-system failures.
Wsaefault:Optval is not a valid part of the process address space.
Wsaeinprogress: a BlockedThe Windows socket interface call is running.
Wsaeinval:The level value is illegal, or the information in the optval is illegal.
Wsaenetreset: The connection timed out when So_keepalive was set.
Wsaenoprotoopt: Unknown or unsupported option. Where thesock_stream type of socket interface does not support the so_broadcast option, thesock_dgram type of socket interface does not support So_dontlinger,so_keepalive, So_linger and so_oobinline options.
Wsaenotconn: The connection is reset when the so_keepalive is set.
Wsaenotsock: The description word is not a set of interfaces.

SetSockOpt usage Explanation

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.