SetSockOpt () function using the detailed

Source: Internet
Author: User

1. closesocket (typically does not close immediately and undergoes a time_wait process) wants to continue reusing 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 is 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 process of sending (), the recv () is sometimes due to network conditions and other reasons, the delivery can not be expected, and set the time to send and receive:
int NNETTIMEOUT=1000;//1 sec
Send Time
setsockopt (Socket,sol_s0cket,so_sndtimeo, (char *) &nnettimeout,sizeof (int));
Receive time limit
setsockopt (Socket,sol_s0cket,so_rcvtimeo, (char *) &nnettimeout,sizeof (int));


4. at the time of Send (), return the byte that is actually sent out (synchronous) or sent to the socket buffer
(asynchronous); The system defaults to send and receive 8688 bytes at a time (approximately 8.5K); Send data in the actual process
and receive a large amount of data, you can set the socket buffer, and avoid send (), recv () Continuous Circulation:
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 are sending data, you want to not experience a copy of the system buffer to the socket buffer
Performance of the program:
int nzero=0;
setsockopt (Socket,sol_s0cket,so_sndbuf, (char *) &nzero,sizeof (Nzero));


6. ditto in recv () 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. in general, when sending a UDP datagram, I hope 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. in the Client Connection server process, if the socket in non-blocking mode in the process of connect () can be
To set the Connect () delay until the Accpet () is called (This function setting is only noticeable in the non-blocking process
function, does not work 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 () did not complete, there is no data sent) and called the Closesocket (), before we
The generally adopted measure is "calmly close" shutdown (S,sd_both), but the data is definitely lost, how to set the program to meet the specific
Application requirements (that is, let the data not sent out after the socket is closed).
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 after the completion of the Allow to stay)
If m_slinger.l_onoff=0, then function and 2.) function the same;
m_slinger.l_linger=5;//(Allowed to stay for 5 seconds)
setsockopt (S,sol_socket,so_linger, (const char*) &m_slinger,sizeof (linger));

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

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: Identifies a descriptive word for a set of interfaces.
Level: The hierarchy of option definitions; currently supports only sol_socket and ipproto_tcp levels.
Optname: Options you want to set.
Optval: Pointer to the buffer that holds the option value.
The length of the optlen:optval buffer.

Comments:
setsockopt() function is used for setting option values for any type, any state set interface. Although there are options on different protocol tiers, this function defines only the highest options on the "set interface" level. Options affect the operation of the socket interface, 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.
Options for two sets of interfaces: One is a Boolean option that allows or disables one attribute, and the other is shaping or structural options. Allows a boolean option to point the optval to a number other than 0, and to prevent an option optval point to an integer equal to zero. For Boolean options, Optlen should equal sizeof (int), and for other options, optval points to the number of plastic or structure that contains the desired option, while Optlen is the number of plastic or the length of the structure. The So_linger option is used to control actions that have queued data to be sent on the socket and that the closesocket () call has been executed. See the effect of the So_linger option on closesocket () semantics in the closesocket () function. The application sets the appropriate operational attributes by creating a linger structure:
struct Linger {
int L_onoff;
int L_linger;
};
To allow So_linger, the application should set the L_onoff to Non-zero, set the L_linger to zero or the required time-out value in seconds, and then call thesetsockopt()。 To allow So_dontlinger (that is, so_linger), L_onoff should be set to zero, and then callsetsockopt()。
By default, a set of interfaces cannot be bundled with a local address that is already in use (see Bind ()). However, there are times when you need to "reuse" addresses. Since each connection is uniquely identified by a combination of local and remote addresses, two sets of interfaces with an address bundle are not a hindrance as long as the remote address is different. To inform the Windows Sleeve interface implementation do not bind an address to another set of interfaces because it is already being used by a nested interface, the application can set the SO_REUSEADDR option before bind () calls. Note that this option is interpreted only when the bind () call is made, so it is not necessary (but harmless) to set this option on a socket that does not share an address, or if bind () has no effect on this or other socket interfaces.
An application can open the So_keepalive option to enable the Windows Socket interface implementation to allow the "keep active" package to be used in the case of a TCP connection. A Windows Sleeve interface implementation is not required to support "keep active", but if supported, the specific semantics will be relevant to the implementation and should comply with the specification of section 4.2.3.6 in the RFC1122 "Internet host requirements-communication layer". If the connection is invalidated due to "keep active", any calls to the set of interfaces in progress will be returned as Wsaenetreset errors, and any subsequent calls will be returned with a wsaenotconn error.
The Tcp_nodelay option prohibits the Nagle algorithm. The Nagle algorithm reduces the number of bits and pieces of small packets sent by the host by storing the unacknowledged data in a buffer until a packet is sent together. But for some applications, this algorithm will reduce system performance. So tcp_nodelay can be used to turn this algorithm off. Application writers set the Tcp_nodelay option only if they know exactly what it's doing and need it, because the setting has a significant negative impact on network performance. Tcp_nodelay is the only option that uses the IPPROTO_TCP layer, and all other options use the Sol_socket layer.
If the So_debug option is set, the Windows socket vendor is encouraged, but not required, to provide the appropriate debugging information for the output. However, the mechanism for generating debugging information and the form of debugging information are beyond the scope of this specification.
setsockopt() supports the following options. Where "type" indicates the type of data that optval refers to.
Option type meaning
So_broadcast BOOL allows the socket interface to transmit broadcast information.
So_debug BOOL Records debugging information.
So_dontliner BOOL do not block the shutdown operation because the data is not sent. Setting this option is equivalent to placing the So_linger l_onoff element to zero.
So_dontroute BOOL is forbidden to choose the path; direct transmission.
So_keepalive BOOL sends the "Keep active" package.
So_linger struct Linger far* If there is no data sent when it is closed, stay.
So_oobinline BOOL receives Out-of-band data in a regular data stream.
The so_rcvbuf int determines the buffer size for the receive.
SO_REUSEADDR BOOL allows a nested interface and an address bundle that is already in use (see Bind ()).
SO_SNDBUF int Specifies the size of the send buffer.
Tcp_nodelay BOOL prohibits the sending of merged Nagle algorithms.

setsockopt() non-supported BSD options are:
Option name Type meaning
So_acceptconn BOOL Sleeve interface in monitoring.
So_error int gets the error status and clears it.
So_rcvlowat int receives a low-level watermark.
So_rcvtimeo int receives timeout.
So_sndlowat int sends a low-level watermark.
So_sndtimeo int sends timeout.
So_type int Sleeve interface type.
Ip_options sets options in the IP header.

return value:
If no error occurs,setsockopt() returns 0. Otherwise, the SOCKET_ERROR error is returned, and the application can obtain the appropriate error code by WSAGetLastError ().

Error code:
Wsanotinitialised: You should first successfully invoke WSAStartup () before using this API.
The Wsaenetdown:windows sleeve interface implementation detects the failure of the network sub system.
Wsaefault:optval is not a valid part of the process address space.
Wsaeinprogress: A blocked Windows Socket interface call is running.
Wsaeinval:level value is illegal, or information in optval is illegal.
Wsaenetreset: The connection timed out after the so_keepalive setting.
Wsaenoprotoopt: Unknown or unsupported option. Where the Sock_stream type's socket does not support the So_broadcast option, the Sock_dgram type's sleeve 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 descriptor is not a nested interface.

See:
Bind (), getsockopt (), ioctlsocket (), socket (), WSAAsyncSelect ().

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

1. If you want to continue reusing a socket that is already in the established state (typically distinguished by a port number and a marker), and then closesocket (which typically does not close immediately and experience a time_wait process), you will:

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 is forced to close after calling Closesocket, the process that does not undergo time_wait is:

BOOL Bdtlger = FALSE;

SetSockOpt (S,sol_socket,so_dontlinger, (const char*) & Bdtlger,sizeof (BOOL));

3. In the process of sending (), the recv () is sometimes due to network conditions and other reasons, the delivery can not be expected, and set the time to send and receive:

int NNETTIMEOUT=1000;//1 sec

Send Time

setsockopt (socket, Sol_s0cket,so_sndtimeo, (char *) &nnettimeout,sizeof (int));

Receive time limit

setsockopt (socket, Sol_s0cket,so_rcvtimeo, (char *) &nnettimeout,sizeof (int));

4. At the time of Send (), returns the byte (synchronous) that is actually sent out or the byte (asynchronous) sent to the socket buffer; The system defaults to send and receive 8688 bytes (about 8.5K) at a time, in the actual process of sending data and receiving data is relatively large, you can set the socket buffer, and to avoid send (), recv () Continuous circular transceiver:

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 are sending data, you want to not experience a copy of the system buffer to the socket buffer to affect the performance of the program:

int nzero=0;

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

6. Ibid. in recv () 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. 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 in the process of connect () can set connect () delay, until Accpet () is called (this function is set only in the process of non-blocking has a significant Used, is not 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 () did not complete, there is no data sent) and called Closesocket (), previously we generally take the measure is "calmly close" shutdown (S,sd_both), but the data is definitely lost, how to set Let the program meet the specific application requirements (that is, let the data not sent out after the socket is closed). The

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 after the completion of the Allow to stay)

if m_slinger.l_onoff=0; then function and 2.) function the same;

m_slinger.l_linger=5;//(Allowed to stay for 5 seconds)

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

Note: 1, in the setting of the stay delay, for a non-blocking socket is not useful, preferably not; 2, if you want the program does not experience so_linger need to set So_dontlinger, or set l_onoff=0;

10. Also a less used in the SDI or Dialog program, you can record the debugging information socket (not long ago, the function of the test, the mode information can be saved, including the socket when the establishment of parameters, the use of specific protocols, and error code can be recorded Down) Then:

BOOL bdebug=true;

SetSockOpt (S,sol_socket,so_debug, (const char*) &bdebug,sizeof (BOOL));

11. For socket Abnormal disconnect (refers to the TCP connection is not graceful way to disconnect, such as network cable failure and other physical links, there are sudden host power outages, and other reasons) there are two ways to detect: 1.TCP connection between the two sides of the timing of the handshake message 2. Using KeepAlive detection in TCP protocol stack the second method is simple and reliable, only the TCP connection two Socket set KeepAlive detection, so this article only said the second method under the LINUX,WINDOW2000 implementation (on the other platform does not make Further testing).

1) Linux

#include

......

KeepAlive implementation

int keepAlive = 1;//Set keepAlive

int keepidle = 5;//start TCP time before first KeepAlive probe

int keepinterval = 5;//time interval between two KeepAlive probes

int keepcount = 3;//Determine the number of KeepAlive probes before disconnecting

if (setsockopt (s,sol_socket,so_keepalive, void*) &keepalive,sizeof (KEEPALIVE)) = = 1)

{

printf ("setsockopt so_keepalive error!/n");

}

if (setsockopt (S,sol_tcp,tcp_keepidle, (void *) &keepidle,sizeof (keepidle)) = = 1)

{

printf ("setsockopt tcp_keepidle error!/n");

}

if (setsockopt (S,SOL_TCP,TCP_KEEPINTVL, (void *) &keepinterval,sizeof (keepinterval)) = = 1)

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.