GetSockOpt and SETSOCKOPT functions in socket in __ function

Source: Internet
Author: User
Tags socket error time limit
Linux below getsockopt/setsockopt function description
Function Description:
Gets or sets the options associated with a socket. Options may exist in multi-tier protocols, and they always appear on the topmost sockets layer. When you manipulate socket options, the names of the layers and options at which the options are located must be given. In order to manipulate the options for the sockets layer, the value of the layer should be specified as Sol_socket. The appropriate protocol number for the control option must be given in order to operate 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 at which the option resides.
Optname: The option name that needs to be accessed.
Optval: For GetSockOpt (), point to a 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 as the entry parameter. The actual length of the option value as an exit parameter. For setsockopt (), the length of the current option.

Return Description:
When successfully executed, returns 0. Failure returns -1,errno is set to one of the following values
Ebadf:sock is not a valid file descriptive word
Efault:optval point to memory is not a valid process space
Einval: Optlen is not valid when setsockopt () is invoked
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock is not describing a socket

Parameters Detailed Description:
level specifies the hierarchy of the control sockets. You can take three 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 allows broadcast data int to be sent
So_debug allows you to debug int
So_dontroute does not find route int
So_error Get socket Error int
So_keepalive remain connected int
So_linger delay close connection struct linger
So_oobinline Out-of-band data into normal data flow 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 allows reuse of local address and Port int
So_type Get socket type int
So_bsdcompat and BSD Systems compatible int
========================================================================
Ipproto_ip
------------------------------------------------------------------------
IP_HDRINCL contains 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 successfully executed, returns 0. Failure returns -1,errno is set to one of the following values
Ebadf:sock is not a valid file descriptive word
Efault:optval point to memory is not a valid process space
Einval: Optlen is not valid when setsockopt () is invoked
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock is not describing a socket

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

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

Attention:
The order of function calls is important when setting the size of the TCP socket receive buffer, because the TCP window sizing option is exchanged with SYN to the other side 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 of explanation:
1. Each set of interfaces has a send buffer and a receive buffer. The receive buffer is used by TCP and UDP to keep the received data from being read by the application process.
tcp:tcp The window size on the other end. The TCP sleeve interface receive buffer cannot overflow because the other side is not allowed to emit more data than the advertised window size. This is the TCP traffic control, and if the other side 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 to receive the buffer. UDP is not flow-controlled; a fast sender can easily drown a slow receiver, causing the receiver's UDP to discard datagrams.
2. We often hear about the TCP protocol three times handshake, but three handshake in the end, what is the details, why do this?
The first time: The client sends the connection request to the server, the server receives;
The second time: the server returns to the client a confirmation code, with a connection request from the server to the client, the client receives, confirms the client to the server connection.
Third time: The client returns the confirmation code that the server last sent the request, the server receives, confirms the server to the client connection.
We can see:
1. Each connection of TCP requires confirmation.
2. Client-side connections to the server and server to the client are independent.
Let's think about the characteristics of the TCP protocol: connected, reliable, Full-duplex, and actually TCP's three handshake to ensure that these features are implemented.
The use of 3.setsockopt
1.closesocket (typically does not close immediately and experience the time_wait process), you want 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 TIME_WAIT process:
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 set connect () delay, until Accpet () is called (this function set only in the process of non-blocking has a significant effect, does not work in blocked 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 up a program to meet the requirements of specific applications (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));
The above article reproduced: http://hi.chinaunix.net/?uid-21832962-action-viewspace-itemid-40517, thank you here.

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.