Linux setsockopt Function

Source: Internet
Author: User
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 you want to force close a soket that is already in the connection status after you call closesocket
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
To set the connect () latency until accpet () is called (this function is set only when there is a significant non-blocking process)
Function 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 ),
The general measure is to "calmly close" Shutdown (S, sd_both), but the data is definitely lost. How to set the program to meet specific requirements?
Application requirements (that is, disable the socket after sending the 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 ));

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

Set Interface Options.

# Include <Winsock. h>

Int Pascal far setsockopt (socket S, int level, int optname,
Const char far * optval, int optlen );

S: Specifies the description of a set of interfaces.
Level: The level defined by the option. Currently, only sol_socket and ipproto_tcp layers are supported.
Optname: the option to be set.
Optval: pointer, pointing to the buffer that stores option values.
Optlen: the length of the optval buffer.

Note:
The setsockopt () function is used to set the option values of interfaces of any type and any status. Although there are options on different protocol layers, this function only defines the options at the highest "set interface" level. This option affects operations on the set interface, such as whether the expedited data is received in a common data stream, and whether the broadcast data can be sent from the set interface.
There are two sets of Interface Options: one is a Boolean option that allows or disables a feature, and the other is an integer or structure option. If a Boolean option is allowed, optval is directed to a non-zero integer.

Optval points to an integer equal to zero. For Boolean options, optlen should be equal to sizeof (INT); for other options, optval points to the integer number containing the required options
Or structure, while optlen is the integer or structure length. The so_linger option is used to control actions in the following situations: sets interfaces with queued data to be sent, and
The closesocket () call has been executed. See the impact of the so_linger option on closesocket () semantics in the closesocket () function. Application
The program creates a linger structure to set the corresponding operation features:
Struct linger {
Int l_onoff;
Int l_linger;
};
In order to allow so_linger, the application should set l_onoff to a non-zero value, set l_linger to zero or the required timeout value (in seconds), and then call
Setsockopt (). To allow so_dontlinger (that is, to disable so_linger), l_onoff should be set to zero and then call
Setsockopt ().
By default, a set of interfaces cannot be bound with a local address in use (see BIND ()). But sometimes it is necessary to "reuse" the address. Because each connection is composed of a local address and a remote address group

As long as the remote address is different, binding two sets of interfaces with one address is not serious. To notify the implementation of Windows interfaces, do not prevent an address from

Another interface bundle allows applications to set the so_reuseaddr option before BIND () is called. Note that this option is interpreted only when BIND () is called.
Set this option for a set interface that does not share the IP address, or set or clear this option if BIND () has no effect on this or other sets of interfaces.
An application can enable the so_keepalive option to enable the "keep active" package for Windows interfaces over TCP connections. One Windows OS
The interface implementation does not need to support "persistence activity". However, if it is supported, the specific semantics will be related to the implementation and should comply with the section in rfc1122 "Internet host requirements-communication layer"
4.2.3.6. If the connection fails due to "active", any call to this interface in progress will be returned with the wsaenetreset error. Any subsequent call
Will be returned with the wsaenotconn error.
The tcp_nodelay option disables the Nagle algorithm. The Nagle algorithm saves unconfirmed data into the buffer until a packet is sent together to reduce the small data fragments sent by the host.

The number of packages. However, for some applications, this algorithm will reduce system performance. Therefore, tcp_nodelay can be used to disable this algorithm. The application writer only needs to know the effect of the application and

The tcp_nodelay option is set only when necessary, because it has a significant negative impact on network performance. Tcp_nodelay is the only option to use the ipproto_tcp layer.
All other options use the sol_socket layer.
If the so_debug option is set, the Windows interface provider is encouraged (but not required) to provide the corresponding debugging information. 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. "Type" indicates the data type specified by optval.
Option type meaning
So_broadcast bool allows an interface to transmit broadcast information.
So_debug bool records debugging information.
So_dontliner bool should not block or close the operation because the data is not sent. Setting this option is equivalent to setting the l_onoff element of so_linger to zero.
So_dontroute bool disallows path selection; direct transfer.
So_keepalive bool sends the "keep active" package.
So_linger struct linger far * stays if no data is sent when it is disabled.
So_oobinline bool receives out-of-band data in a conventional data stream.
So_rcvbuf int determines the buffer size for receiving.
So_reuseaddr bool allows you to bind an interface with an existing address (see BIND ()).
So_sndbuf int specifies the size of the sending buffer.
Tcp_nodelay bool prohibits the combined Nagle algorithm from being sent.

Setsockopt () does not support the following BSD options:
Option name type meaning
The so_acceptconn bool interface is monitored.
So_error INT: Get the error status and clear it.
So_rcvlowat int receives low-level watermarks.
So_rcvtimeo int timeout.
So_sndlowat int sends a low-level watermark.
So_sndtimeo int timeout.
So_type int set interface type.
Set ip_options in the IP header.

Return Value:
If no error occurs, setsockopt () returns 0. Otherwise, the socket_error is returned. The application can obtain the error code through wsagetlasterror.

Error code:
Wsanotinitialised: before using this API, you must successfully call wsastartup ().
Wsaenetdown: A Windows interface is used to detect the failure of the network subsystem.
Wsaefault: optval is not a valid part of the process address space.
Wsaeinss SS: A blocked Windows interface call is running.
Wsaeinval: The level value is invalid, or the information in optval is invalid.
Wsaenetreset: the connection times out when so_keepalive is set.
Wsaenoprotoopt: unknown or not supported. Sock_stream APIs do not support so_broadcast and sock_dgram.
The so_dontlinger, so_keepalive, so_linger, and so_oobinline options are not supported.
Wsaenotconn: When so_keepalive is set, the connection is reset.
Wsaenotsock: The description is not a set of interfaces.

See:
BIND (), getsockopt (), ioctlsocket (), socket (), wsaasyncselect ().

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.