UNP summary Chapter 7 socket options

Source: Internet
Author: User
Tags socket error

 

1. getsockopt and setsockopt Functions

These two functions are only used for sockets:

# Include <sys/socket. h> int getsockopt (int sockfd, int level, int optname, void * optval, socklen_t * optlen); int setsockopt (int sockfd, int level, int optname, const void * optval socklen_t optlen); // all return: If the success is 0, the error is-1

Sockfd must point to an open socket descriptor, level (level) that specifies the code for interpreting options in the system, common socket code, or protocol-specific code, optval is a pointer to a variable (* optval). setsockopt obtains the new value of the option to be set from * optval. getsockopt stores the current value of the obtained option to * optval, * The optval size is specified by the last optlen parameter. It is a value parameter for setsockopt and a value-result parameter for getsockopt.

Socket options are roughly divided into two basic types: one is to enable or disable a feature of the Second Hospital option (become a flag option ), the second is to obtain and return options (called value options) of specific values that we can set or check)

* Optval is an integer when the getsockopt function is called. * The value returned by optval is 0, indicating that the corresponding option is disabled. If it is not 0, the corresponding item is enabled. Similarly, the setsockopt function requires an option in * optval value not 0, and an * optval value of 0 to disable the option.

In short, the above two functions control socket behavior by controlling socket options (such as modifying the buffer size ). Here are their function descriptions:

Obtain or set the options associated with a socket. Options may exist in multi-layer protocols, and they will always appear at the top socket layer. When you operate on socket options, the layer at which the options are located and the name of the options must be provided. To operate the socket layer options, specify the layer value as SOL_SOCKET. In order to operate on the options of other layers, the appropriate Protocol Number of the control options must be given.

The above content is the original UNP. Here we will summarize the parameters.

Parameters:

Sock: the socket for which the options will be set or obtained.

Level: the protocol layer of the option.

Optname: name of the option to be accessed.

Optval: For getsockopt (), the buffer pointing to the returned option value. For setsockopt (), point to the buffer containing the new option value.

Optlen: the maximum length of the option value when getsockopt () is used as the entry parameter. The actual length of the option value when it is used as an exit parameter. For setsockopt (), the length of the current option.

 

Return description:

0 is returned when execution is successful. -1 is returned for failure, and errno is set to one of the following values

EBADF: sock is not a valid file description.

EFAULT: the memory to which optval points is not a valid process space

EINVAL: optlen is invalid when setsockopt () is called.

ENOPROTOOPT: the specified protocol layer does not recognize the option.

ENOTSOCK: sock does not describe socket

 

 

 

 

 

2. Common, IPv4, and TCP socket options

Level specifies the level of the control socket. There are three common values:

1) SOL_SOCKET: General socket options.

2) IPPROTO_IP: IP Option.

3) IPPROTO_TCP: TCP option.

 

For a summary of common socket options compiled from the Internet, see UNP3)

Option Name Description Data Type
========================================================== ======================================
SOL_SOCKET
------------------------------------------------------------------------
SO_BROADCAST allows sending broadcast data int
SO_DEBUG allows int debugging
SO_DONTROUTE
SO_ERROR get socket error int
SO_KEEPALIVE
SO_LINGER delay disconnection struct linger
SO_OOBINLINE put out-of-band data into normal data stream int
SO_RCVBUF receive buffer size int
SO_SNDBUF sending buffer size int
SO_RCVLOWAT lower limit int of the receiving buffer
SO_SNDLOWAT lower limit int of the sending Buffer
SO_RCVTIMEO receiving timeout struct timeval
SO_SNDTIMEO sending timeout struct timeval
SO_REUSERADDR allows reuse of the local address and port int
SO_TYPE: Obtain the socket type int.
SO_BSDCOMPAT is compatible with the BSD system int
========================================================== ======================================
IPPROTO_IP
------------------------------------------------------------------------
IP_HDRINCL contains the IP header int in the data package.
IP_OPTINOS IP header option int
IP_TOS service type
IP_TTL time int
========================================================== ======================================
IPPRO_TCP
------------------------------------------------------------------------
TCP_MAXSEG maximum TCP Data Segment Size int
TCP_NODELAY does not use the Nagle algorithm int
========================================================== ======================================

 

 

 

Some details:

1). SO_LINGER

This option specifies how the function close operates on connection-oriented protocols (such as TCP ). The default close operation of the kernel returns immediately. If any data remains in the interface buffer, the system will try to send the data to the other party.

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

struct linger {     int l_onoff;    /* 0 = off, nozero = on */     int l_linger;   /* linger time */};

 

There are three situations:

A. if l_onoff is set to 0, this option is disabled. The value of l_linger is ignored, which is equal to the kernel default. The close call will be immediately returned to the caller, and if possible, any unsent data will be transmitted;

B. if Rochelle off is set to non-0 and Rochelle linger is set to 0, TCP will abort the connection when the set interface is closed. TCP will discard any data retained in the buffer sent by the set interface and send an RST to the other party, instead of the usual four-group termination sequence, this avoids the TIME_WAIT status;

C. Set l_onoff to non-0 and l_linger to non-0. When the set of interfaces is disabled, the kernel will be delayed for a period of time (determined by l_linger ). If data remains in the interface buffer, the process will be in sleep state, straight

  • After all the data is sent and confirmed by the other party, a normal termination sequence is followed (the descriptive word access count is 0)
  • The delay time is up. In this case, it is very important for the application to check the return value of close. If the time is up before the data is sent and confirmed, close will return the EWOULDBLOCK error, and any data in the sending buffer zone of the interface is lost.

The successful return of close only tells us that the data (and FIN) sent has been confirmed by the other party's TCP. It does not tell us whether the other party's application process has read the data. If the set of interfaces is set to non-blocking, it will not wait for close to complete. (For details, see UNP)

 

2). SO_RCVBUF and SO_SNDBUF

When sending (), the returned bytes are actually sent out bytes (synchronized) or the bytes (asynchronous) sent to the socket buffer ); the default sending and receiving status is 8688 bytes (about 8.5 KB). In the actual process, the sending and receiving data volume is large. You can set the socket buffer, instead of sending () and recv () in a loop:

// Receive the buffer int nRecvBuf = 32*1024; // set it to 32 Ksetsockopt (s, SOL_SOCKET, SO_RCVBUF, (const char *) & nRecvBuf, sizeof (int )); // sending buffer int nSendBuf = 32*1024; // set it to 32 Ksetsockopt (s, SOL_SOCKET, SO_SNDBUF, (const char *) & nSendBuf, sizeof (int ));

 

3). SO_REUSEADDR

Closesocket (usually does not close immediately and goes through the TIME_WAIT process) and wants to continue to reuse the socket:

BOOL bReuseaddr=TRUE;setsockopt(s,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL));

 

4). SO_BROADCAST

Closesocket (usually does not close immediately and goes through the TIME_WAIT process) and wants to continue to reuse the socket:

BOOL bReuseaddr=TRUE;setsockopt(s,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL));

 

5). SO_RCVBUF and SO_SNDBUF

When sending (), the returned bytes are actually sent out bytes (synchronized) or the bytes (asynchronous) sent to the socket buffer ); the default sending and receiving status is 8688 bytes (about 8.5 KB). In the actual process, the sending and receiving data volume is large. You can set the socket buffer, instead of sending () and recv () in a loop:

// Receive the buffer int nRecvBuf = 32*1024; // set it to 32 Ksetsockopt (s, SOL_SOCKET, SO_RCVBUF, (const char *) & nRecvBuf, sizeof (int )); // sending buffer int nSendBuf = 32*1024; // set it to 32 Ksetsockopt (s, SOL_SOCKET, SO_SNDBUF, (const char *) & nSendBuf, sizeof (int ));

 

 

6). SO_RCVTIMEO and SO_SNDTIMEO

In the send (), recv () process, sometimes due to network conditions and other reasons, sending and receiving cannot be expected, but set the sending and receiving time limit:

Int nNetTimeout = 1000; // 1 second // setsockopt (socket, SOL_S0CKET, SO_SNDTIMEO, (char *) & nNetTimeout, sizeof (int )); // receipt time limit setsockopt (socket, SOL_S0CKET, SO_RCVTIMEO, (char *) & nNetTimeout, sizeof (int ));

 

7). SO_DONTLINGER

If you want to force close a soket that is already in the connection state after you call closesocket, it does not go through the TIME_WAIT process:

BOOL bDontLinger = FALSE;setsockopt(s,SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));

 

8). IP_RECVDSTADDR

Setting this socket option causes the destination IP address of the received UDP datagram to be returned by the recvmsg function as the secondary data

 

 

9 ).TCP_MAXSEG
Gets or sets the maximum number of nodes (MSS) for a TCP connection ). The returned value is the maximum data volume that our TCP sends to the other end.It is usually the MSS advertised by the other end using SYN, unless we select a value smaller than the MSS advertised by the other end. If this value is obtained before the set interface connection, the returned value is the default value when the Mss option is not received from the other end. A message smaller than the returned value can be used for connections, because a token occupies 12 bytes of TCP option capacity in each shard if the timestamp option is used.

 

 

10 ).TCP_NODELAY

Enabling this option will disable the TCP Nagle algorithm. By default, this algorithm is enabled.

Nagle algorithm, which indicates that if data is to be confirmed on a given connection, the behavior of sending a response to a small group immediately on the connection, which should be the response of the user's write operation, will not happen, until the existing data is confirmed

TCP communication when the Nagle algorithm is enabled

TCP communication when the Nagle algorithm is disabled

PS:

The socket option that corresponds to TCP_NODELAY --- TCP_CORK: it is a enhanced nagle algorithm. The process is similar to the nagle algorithm, where data is accumulated and then sent. But it does not have the limit of 1 in nagle. Therefore, after setting cork, even if all ack has been received, I still don't want to send data, I still want to wait for more data on the application layer, so it works better than nagle.

 

3. fcntl Functions

This function is introduced in the APUE topic. Only Network Programming features related to the fcntl letter are listed here.

  • Non-blocking I/O. By using the F_SETFL command to set the O_NONBLOCK File status flag, we can set a socket to a non-blocking type.
  • Signal-driven I/O. By using the F_SETFL command to set the O_ASYNC File status flag, we can set a socket to generate a SIGIO signal once its status changes.
  • The F_SETOWN command allows us to specify the process ID or group ID used to receive SIGIO and SIGURG signals ,. The SIGIO signal is generated after the socket is set as a signal-driven I/O type, and the SIGURG signal is generated when the new outbound data arrives at the socket.
# Include <fcntl. h> int fcntl (intfd, int cmd,.../* int arg */); // return: if the result is successful, it depends on cmd. Error-1

Each Descriptor (including socket descriptor) has a set of file flags obtained by the F_GETFL command or set by the F_SETFL command. The two symbols that affect the socket descriptor are:

  • O_NONBLOCK -------- non-blocking I/O
  • O_ASYNC ------------- signal-driven I/O

 

Use fcntl to enable non-blocking I/O typical code

int     flags;     /* Set a socket as nonblocking */if  ( (flags = fcntl (fd, F_GETFL, 0)) < 0)    err_sys("F_GETFL error");flags |= O_NONBLOCK;if (fcntl(fd, F_SETFL, flags) < 0)    err_sys("F_SETFL error");

 

You may encounter code that is simple to set the desired identifier, but it is an incorrect method. The correct method is to obtain the current identifier first, and then set the identifier with the new identifier logic or later.

   /* Wrong way to set a socket as nonblocking */if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)    err_sys("F_SETFL error");

 

The following code disables the non-blocking flag. Assume that flags is set by the fcntl call shown above.

int     flags;

     /* Set a socket as nonblocking */
if  ( (flags = fcntl (fd, F_GETFL, 0)) < 0)
    err_sys("F_GETFL error");

flags &= ~O_NONBLOCK;if (fcntl(fd, F_SETFL, flags) < 0) err_sys("F_SETFL error");

 

 

 

 

 

 

 

 

 

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.