setsockopt() — Set options associated with a socket

Standards

Standards / Extensions C or C++ Dependencies

XPG4.2
Single UNIX Specification, Version 3

both  

Format

X/Open:
#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>

int setsockopt(int socket, int level, int option_name,
               const void *option_value, socklen_t option_length);
Berkeley sockets:
#define _OE_SOCKETS
#include <sys/types.h>
#include <sys/socket.h>

int setsockopt(int socket, int level, int option_name,
               char *option_value, int *option_length);
IPv6: To include support for IPv6 socket options, add the following code:
#define _OPEN_SYS_SOCK_IPV6 1
#include <netinet/in.h>
ip_mreq structure: To include the ip_mreq structure in your program, add the following code:
#define _XOPEN_SOURCE  500
#include <netinet/in.h>
or
#define _OPEN_SYS_SOCK_EXT3
#include <netinet/in.h>
group_req structure: To include the group_req structure in your program, add the following code:
#define _OPEN_SYS_SOCK_EXT3
#include <netinet/in.h>
group_source_req structure: To include the group_source_req structure in your program, add the following code:
#define _OPEN_SYS_SOCK_EXT3
#include <netinet/in.h>
ipv6_mreq structure: To include the ipv6_mreq structure in your program, add the following code:
#define _OPEN_SYS_SOCK_IPV6
#include <netinet/in.h>
icmp6_filter structure: To include the icmp6_filter structure in your program, add the following code:
#define _OPEN_SYS_SOCK_IPV6
#include <netinet/icmp6.h>

General description

The setsockopt() function sets options associated with a socket. Options can exist at multiple protocol levels.
Parameter
Description
socket
The socket descriptor.
level
The level for which the option is being set.
option_name
The name of a specified socket option.
option_value
The pointer to option data.
option_length
The length of the option data.

When manipulating socket options, you must specify the level at which the option resides and the name of the option. To manipulate options at the socket level, the level parameter must be set to SOL_SOCKET as defined in sys/socket.h. To manipulate options at the IPv4 or IPv6 level, the level parameter must be set to IPPROTO_IP as defined in sys/socket.h or IPPROTO_IPV6 as defined in netinet/in.h. To manipulate options at any other level, such as the TCP level, supply the appropriate protocol number for the protocol controlling the option. The getprotobyname() call can be used to return the protocol number for a named protocol.

The option_value and option_length parameters are used to pass data used by the particular set command. The option_value parameter points to a buffer containing the data needed by the set command. The option_value parameter is optional and can be set to the NULL pointer, if data is not needed by the command. The option_length parameter must be set to the size of the data pointed to by option_value.

All of the socket-level options except SO_LINGER, SO_RCVTIMEO and SO_SNDTIMEO, expect option_value to point to an integer and option_length to be set to the size of an integer. When the integer is nonzero, the option is enabled. When it is zero, the option is disabled. The SO_LINGER option expects option_value to point to a linger structure, as defined in sys/socket.h. This structure is defined in the following example:
struct  linger
{
        int     l_onoff;                /* option on/off */
        int     l_linger;               /* linger time */
};

The l_onoff field is set to 0 if the SO_LINGER option is begin disabled. A nonzero value enables the option. The l_linger field specifies the amount of time to linger on close. The units of l_linger are seconds.

The following options are recognized at the IPv4 level:
Option
Description
IP_ADD_MEMBERSHIP
(RAW and UDP) This option is used to join a multicast group on a specific interface (an interface has to be specified with this option). Only applications that want to receive multicast datagrams need to join multicast groups. Applications that only transmit will not need to do so.
The multicast IP address and the interface IP address will be passed in the following structure available in netinet/in.h:
struct ip_mreq
{
   struct in_addr imr_multiaddr; /* IP multicast addr of group */
   struct in_addr imr_interface; /* local IP addr of interface */
};
If INADDR_ANY is specified on the interface address of the mreq structure passed a default interface will be chosen as follows:
  • If the group address specified in the mreq structure was specified on a GATEWAY statement use that interface.
  • If 224.0.0.0 was specified on GATEWAY statement use that interface.
  • If DEFAULTNET was specified and is multicast capable use that interface.
IP_ADD_SOURCE_MEMBERSHIP
(RAW and UDP) This option is used to join a source-specific multicast group specified by the ip_mreq_source structure. The ip_mreq_source structure is defined in netinet/in.h.
IP_BLOCK_SOURCE
(RAW and UDP) This option is used to block from a given source to a given multicast group (e.g., if the user "mutes" that source). The source multicast group is specified by the ip_mreq_source structure which is defined in netinet/in.h.
IP_DROP_MEMBERSHIP
(RAW and UDP) This option is used to leave a multicast group.
The multicast IP address and the interface IP address will be passed in the following structure available in netinet/in.h:
struct ip_mreq
{
   struct in_addr imr_multiaddr; /* IP multicast addr of group */
   struct in_addr imr_interface; /* local IP addr of interface */
};

If INADDR_ANY is specified on the interface address of the mreq structure passed the system will drop the first group that matches the group (class D) address without regard to the interface.

IP_DROP_SOURCE_MEMBERSHIP
(RAW and UDP) This option is used to leave a source-specific multicast group specified by the ip_mreq_source structure. The ip_mreq_source structure is defined in netinet/in.h.
IP_MULTICAST_IF
(RAW and UDP) Sets the interface for sending outbound multicast datagrams from this socket application. Multicast datagrams will be transmitted only on one interface at a time. An IP address is passed in an in_addr structure.
If INADDR_ANY is specified for the interface address passed a default interface will be chosen as follows:
  • If 224.0.0.0 was specified on GATEWAY statement use that interface.
  • If DEFAULTNET was specified and is multicast capable use that interface.
IP_MULTICAST_LOOP
(RAW and UDP) Enables or disables loopback of outgoing multicast datagrams. Default is enable. When it is enabled, multicast applications that have joined the outgoing multicast group can receive a copy of the multicast datagrams destined for that address/port pair. The loopback indicator is passed as an u_char. The value 0 is specified to disable loopback. The value 1 is specified to enable loopback.
IP_MULTICAST_TTL
(RAW and UDP) Sets the IP time-to-live of outgoing multicast datagrams. Default value is 1 (that is, multicast only to the local subnet). The TTL value is passed as an u_char.
IP_RECVPKINFO
(RAW and UDP) Enables or disables returning the destination IP address of an incoming packet and the interface over which the packet was received as IP_PKTINFO ancillary data on recvmsg() function calls. The option value is specified as an int. A nonzero value enables the option; 0 disables the option.

This option is protected by the _OPEN_SYS_SOCK_EXT4 feature test macro.

IP_UNBLOCK_SOURCE
(RAW and UDP) This option is used to undo the operation performed with the IP_BLOCK_SOURCE option (e.g., if the user "mutes" that source). The source group is specified by the ip_mreq_source structure which is defined in netinet/in.h.
MCAST_BLOCK_SOURCE
(RAW and UDP) This option is used to block data from a given source to a given group (e.g., if the user "mutes" that source). The source is specified by the group_source_req structure which is defined in netinet/in.h.
MCAST_JOIN_GROUP
(RAW and UDP) This option is used to join an any-source group. The group is specified by the group_req structure. The group_req structure is defined in netinet/in.h.
MCAST_JOIN_SOURCE_GROUP
(RAW and UDP) This option is used to join a source-specific group. The source is specified by the group_source_req structure which is defined in netinet/in.h.
MCAST_LEAVE_GROUP
(RAW and UDP) This option is used to to leave an any-source group. The group is specified by the group_req structure. The group_req structure is defined in netinet/in.h.
MCAST_LEAVE_SOURCE_GROUP
(RAW and UDP) This option is used to leave a source-specific group. The source is specified by the group_source_req structure which is defined in netinet/in.h.
MCAST_UNBLOCK_SOURCE
(RAW and UDP) This option is used to undo the operation performed with the MCAST_BLOCK_SOURCE option (e.g., if the user then "unmutes" the source). The source is specified by the group_source_req structure which is defined in netinet/in.h.

The following options are recognized at IPv6 level:

Option
Description
IPV6_ADDR_PREFERENCES
(TCP and UDP) Used to set the source address selection preference flags for a given socket. The socket option value (optval) is a 32-bit unsigned integer argument. The argument consists of a number of flags where each flag indicates a source address selection preference. These flags indicate the application's preferences for a source address, but will be ignored by the TCP stack if an IP address with the preferred address attributes is not available. For example, a preference flag of IPV6_PREFER_SRC_TMP tells the stack that the application would prefer to use a temporary IPv6 source address rather than a public source address. You can combine multiple flags with logical OR to express multiple preferences as long as the flags are not contradictory. The constants for the flag bit values are defined in netinet/in.h.
IPV6_CHECKSUM
(RAW) For a RAW (non-ICMPv6) socket, this option instructs the kernel to compute and store a checksum for output and verifies the received checksum on input. This prevents applications from having to perform source address selection on the packets sent. This option specifies an integer value into the user data where the checksum is located. This option can be disabled by specifying an option value of -1.
IPV6_DONTFRAG
(RAW and UDP) This option turns off the automatic inserting of a fragment header in the packet for UDP and raw sockets.
IPV6_DSTOPTS
(RAW and UDP) The application can remove any sticky destination options header by calling setsockopt() for this option with a zero option length.
IPV6_HOPOPTS
(RAW and UDP) The application can remove any sticky hop-by-hop options header by calling setsockopt() for this option with a zero option length.
IPV6_JOIN_GROUP
(RAW and UDP) Controls the receipt of multicast packets by joining the multicast group specified by the ipv6_mreq structure that is passed. The ipv6_mreq structure is defined in netinet/in.h.
IPV6_LEAVE_GROUP
(RAW and UDP) Controls the receipt of multicast packets by leaving the multicast group specified by the ipv6_mreq structure that is passed. The ipv6_mreq structure is defined in netinet/in.h.
IPV6_MULTICAST_HOPS
(RAW and UDP) Sets the hop limit for outgoing multicast packets. The hop limit value is passed as an int.
IPV6_MULTICAST_IF
(RAW and UDP) Sets the interface for outgoing multicast packets. An interface index is used to specify the interface. It is passed as an u_int.
IPV6_MULTICAST_LOOP
(RAW and UDP) If a multicast datagram is sent to a group to which the sending host itself belongs (on the outgoing interface), a copy of the datagram is looped back by the IP layer for local delivery if this option is set to one. If this option is set to zero, a copy is not looped back. Other option values return an errno of EINVAL. The default is one (loopback). The option value is passed as an int.
IPV6_NEXTHOP
(RAW and UDP) Specifies the next hop for the datagram as a socket address structure.
IPV6_RECVDSTOPTS
(RAW and UDP) To receive destination options header this option must be enabled.
IPV6_RECVHOPLIMIT
(RAW, TCP, and UDP) When this option is enabled, the received hop limit from an incoming packet will be returned as IPV6_HOPLIMIT ancillary data on recvmsg() function calls. The option value is specified as an int. A nonzero value enables the option, zero disables the option.
IPV6_RECVHOPOPTS
(RAW and UDP) To receive a hop-by-hop options header this option must be enabled.
IPV6_RECVPATHMTU
(RAW and UDP) Enables the receipt of IPV6_PATHMTU ancillary data on recvmsg() function calls.
IPV6_RECVPKTINFO
(RAW and UDP) Enables or disables returning the destination IP address of an incoming packet and the interface over which the packet was received as IPV6_PKTINFO ancillary data on recvmsg() function calls. The option value is specified as an int. A nonzero value enables the option; 0 disables the option.
IPV6_RECVRTHDR
(RAW and UDP) To receive a routing header this option must be enabled.
IPV6_RECVTCLASS
(RAW, TCP, and UDP) To receive the traffic class this option must be enabled.
IPV6_RTHDR
(RAW and UDP) The application can remove any sticky routing header by calling setsockopt() for this option with a zero option length.
IPV6_RTHDRDSTOPTS
(RAW and UDP) The application can remove any sticky destination options header by calling setsockopt() for this option with a zero option length.
IPV6_TCLASS
(RAW, TCP, and UDP) To specify the traffic class value this option must be enabled.
IPV6_UNICAST_HOPS
(RAW and UDP) Used to control hop limit in outgoing unicast IPv6 packets. The hop limit value is passed as an int.
IPV6_USE_MIN_MTU
(RAW, TCP, and UDP) Indicates whether the IP layer will use the minimu MTU size (1280) for sending packets, bypassing path MTU discovery. The option value is passed as an int. A value of -1 causes the default values for unicast (disabled) and multicast (enabled) destinations to be used. A value of 0 disables this option for unicast and multicast destinations. A value of 1 enables this option for unicast and multicast destinations and the minimum MTU size will be used.
IPV6_V6ONLY
(RAW. TCP, and UDP) Used to determine whether a socket is restricted to IPv6 communications only. The default setting is off. The option value is passed as an int. A non-zero value means the option is enabled (socket can only be used for IPv6 communications). 0 means the option is disabled.
Note: To use these options, you must use the feature test macro #define _OPEN_SYS_SOCK_IPV6.
The following options are recognized at the ICMPv6 level:
Option
Description
ICMP6_FILTER
(RAW) Used to filter ICMPv6 messages. The option value is passed as an icmp6_filter structure. The icmp6_filter structure is defined in netinet/icmp6.h.
The following options are recognized at the socket level:
Option
Description
SO_BROADCAST
Toggles the ability to broadcast messages. If enabled, this option allows the application program to send broadcast messages over socket, if the interface specified in the destination supports broadcasting of packets. This option has no meaning for stream sockets.
SO_DEBUG
Turns on recording of debugging information. This option enables or disables debugging in the underlying protocol modules. This option takes an int value.
SO_KEEPALIVE
Toggles the TCP keep-alive mechanism for a stream socket. When activated, the keep-alive mechanism periodically sends a packet on an otherwise idle connection. If the remote TCP does not respond to the packet or to retransmissions of the packet, the connection is terminated with the error ETIMEDOUT.
SO_LINGER
Lingers on close if data is present. When this option is enabled and there is unsent data present when close() is called, the calling application program is blocked during the close() call, until the data is transmitted or the connection has timed out. If this option is disabled, the TCP/IP address space waits to try to send the data. Although the data transfer is usually successful, it cannot be guaranteed, because the TCP/IP address space waits only a finite amount of time trying to send the data. The close() call returns without blocking the caller. This option has meaning only for stream sockets.
SO_OOBINLINE
Toggles the reception of out-of-band data. When this option is enabled, it causes out-of-band data to be placed in the normal data input queue as it is received, making it available to recv(), recvfrom(), and recvmsg() without having to specify the MSG_OOB flag in those calls. When this option is disabled, it causes out-of-band data to be placed in the priority data input queue as it is received, making it available to recv(), recvfrom(), and recvmsg() only by specifying the MSG_OOB flag in those calls. This option has meaning only for stream sockets.
_SO_PROPAGATEUSERID
Toggles propagating a user ID (UID) over an AF_UNIX stream socket. When enabled, user (UID) information is extracted from the system when the connect() function is invoked. Then, when the accept() function is invoked, the accepter assumes the identity of the connecter until the accepted socket is closed.
SO_RCVBUF
Sets receive buffer size. This option takes an int value. The value cannot be set after the socket is connected.
SO_RCVTIMEO

Sets the timeout specifying the maximum amount of time an input function waits until it completes.

It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. The timeval structure contains the number of seconds and microseconds specified as fullword binary numbers. The seconds can be a value in the range from 0 to 2,678,400 (equal to 31 days), and the microseconds can be a value in the range from 0 to 1,000,000 (equal to 1 second). While the timeval structure can be specified using mircosecond granularity, the internal TCP/IP timers used to implement this function have a granularity of approximately 100 milliseconds.

If a receive operation has blocked for this much time without receiving additional data, it returns with a partial count or errno set to EWOULDBLOCK if no data is received. The default for this option is zero, which indicates that a receive operation does not time out.

SO_REUSEADDR

Toggles local address reuse. When enabled, this option allows local addresses that are already in use to be bound. This alters the normal algorithm used in the bind() call.

The system checks at connect time to ensure that the local address and port do not have the same foreign address and port. The error EADDRINUSE is returned if the association already exists.

After the SO_REUSEADDR option is active, the following situation is supported:

A server can bind() the same port multiple times as long as every invocation uses a different local IP address and the wildcard address INADDR_ANY is used only one time per port.

SO_SNDBUF
Sets send buffer size. This option takes an int value. The value cannot be set after the socket is connected.
SO_SNDTIMEO

Sets the timeout value specifying the amount of time that an output function blocks due to flow control preventing data from being sent.

It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. The timeval structure contains the number of seconds and microseconds specified as fullword binary numbers. The seconds can be a value in the range from 0 to 2,678,400 (equal to 31 days), and the microseconds can be a value in the range from 0 to 1,000,000 (equal to 1 second). While the timeval structure can be specified using mircosecond granularity, the internal TCP/IP timers used to implement this function have a granularity of approximately 100 milliseconds.

If a send operation has blocked for this time, it returns with a partial count or with errno set to EWOULDBLOCK if no data is sent. The default for this option is zero, which indicates that a send operation does not time out.

SO_SECINFO
Toggles receiving security information. When enabled on an AF_UNIX UDP socket, the recvmsg() function will return security information about the sender of each datagram as ancillary data. This information contains the sender's user ID, UID, GID, and job name and it is mapped by the secsinfo structure in sys/socket.h.
Note: To use these options, you must use the Feature Test Macro #define _OPEN_SYS_SOCK_IPV6.

Special behavior for C++: To use this function with C++, you must use the _XOPEN_SOURCE_EXTENDED 1 feature test macro.

Returned value

If successful, setsockopt() returns 0.

If unsuccessful, setsockopt() returns -1 and sets errno to one of the following values:
Error Code
Description
EADDRNOTAVAIL
The ipi6_addr is not available for use on the ipi6_ifindex interface or the tuple consisting of socket, interface, and multicast group values does not exist..
EBADF
The socket parameter is not a valid socket descriptor.
EDOM
The send or receive timeout values exceed 31 days.
EFAULT
Using option_value and option_length parameters would result in an attempt to access storage outside the caller's address space.
EHOSTUNREACH
No route to the destination exists over the interface specified by ifi6_ifindex.
EINVAL
The specified option is invalid at the specified socket level or the socket has been shut down.
ENETDOWN
The interface specified by ipi6_ifindex is not enabled for IPv6 use.
ENOBUFS
Insufficient system resources are available to complete the call or a maximum of 64 source filters can be specified per multicast group, interface pair.
ENOPROTOOPT
The option_name parameter is unrecognized, or the level parameter is not SOL_SOCKET.
ENOSYS
The function is not implemented. You attempted to use a function that is not yet available.
ENOTSOCK
The descriptor is for a file, not for a socket.
ENXIO
The interface specified by ipi6_ifindex does not exist.

Example

The following are examples of the setsockopt() call. See getsockopt() — Get the options associated with a socket for examples of how the getsockopt() options set are queried.
int rc;
int s;
int option_value;
struct linger l;
int setsockopt(int s, int level, int option_name, 
char *option_value,
     int option_len);
⋮
/* I want out of band data in the normal input queue */
option_value = 1;
rc = setsockopt(s, SOL_SOCKET, SO_OOBINLINE, 
(char *) &option_value, sizeof(int));

⋮
/* I want to linger on close */
l.l_onoff  = 1;
l.l_linger = 100;
rc = setsockopt(s, SOL_SOCKET, SO_LINGER, 
(char *) &l, sizeof(l));

Related information