Socket provides two functions to control socket behavior. One is used to set options and the other is used to query the status of one socket option.
The following three options can be set or queried:
- Common options that work on all socket types.
- The options for Socket Layer Management depend on the support of the underlying protocol.
- Specific protocol options.
1. Set the socket option function:
- Header file: <sys/socket. h>
- Prototype: int setsockopt (INT sockfd, int level, int option, const void * val, socklen_t Len );
- Return Value: 0 is returned if the request is successful, and-1 is returned if an error occurs.
- Parameters:
- Level: indicates the Protocol (layer) of the Option application ).
- For general options, set level to sol_socket.
- Otherwise, set the Protocol Number to control this option, for example:
- TCP: ipproto_tcp
- IP: ipproto_ip.
- Option: socket option. For details, refer to the apue 465 page table.
- VAL: points to a struct or an int based on different options.
- Len: the size of the object to which Val points.
2. query the socket option function:
- Header file: <sys/socket. h>
- Prototype: int getsockopt (INT sockfd, int level, int option, void * restrict Val, socklen_t * restrict lenp );
- Return Value: 0 is returned if the request is successful, and-1 is returned if an error occurs.
- Parameters:
- Lenp: pointer to an integer. Set this integer to the buffer size of the storage option before getsockopt is executed.
- If the actual size is greater than this value, the option will be truncated without an error.
- If the actual size is smaller than or equal to this value, the returned value is updated to the actual size.
Appendix:
Socket option table
Option |
Parameter Val type |
Description |
So_acceptconn |
Int |
The returned information indicates whether the socket can be listened to (getsockopt only) |
So_broadcast |
Int |
If * Val is not 0, broadcast data packets |
So_debug |
Int |
If * Val is not 0, enable the network driver debugging function. |
So_dontroute |
Int |
If * Val is not 0, common routes are bypassed. |
So_error |
Int |
The suspended socket error is returned and clear (getsockopt only) |
So_keepalive |
Int |
If * Val is not 0, enable periodic keep-alive messages |
So_linger |
Struct linger |
Latency when a message is not sent and the socket is disabled |
So_oobinline |
Int |
If * Val is not 0, put out-of-band data in normal data. |
So_rcvbuf |
Int |
Size of the receiving buffer in bytes |
So_rcvlowat |
Int |
Minimum Data size in bytes returned by receiving calls |
So_rcvtimeo |
Struct timeval |
Timeout value of the socket Receiving call |
So_reuseaddr |
Int |
If * Val is not 0, reuse the address in BIND. |
So_sndbuf |
Int |
Size of the sending buffer in bytes |
So_sndlowat |
Int |
Minimum Data size sent in bytes in a sending call |
So_sndtimeo |
Struct timeval |
Timeout value of the socket sending call |
So_type |
Int |
Identifies the socket type (getsockopt only) |