socket(7)

๐ŸŒˆ socket(7) ๐ŸŒˆ

okay bestie, sit down, hydrate, and get comfy โ€” this is socket(7), from the Miscellaneous Information Manual, and it's literally the user-facing manual for the Linux networking socket layer. It's a big one so we're doing it in parts, and this is part one. Buckle up ๐Ÿ’…


โœจ NAME โœจ

socket โ€” the Linux socket interface ๐Ÿซถ


โœจ SYNOPSIS โœจ

#include <sys/socket.h>

sockfd = socket(int socket_family, int socket_type, int protocol);

โœจ DESCRIPTION โœจ

So here's the tea, bestie: this page is all about the Linux networking socket layer user interface. The BSD-compatible sockets are that uniform interface sitting between your lil user process and the network protocol stacks hanging out inside the kernel. ๐Ÿงš

The protocol modules get sorted into protocol families โ€” think AF_INET, AF_IPX, AF_PACKET โ€” and socket types like SOCK_STREAM or SOCK_DGRAM. Want the full lore on families and types? That's socket(2), go read it. ๐Ÿ“š


๐ŸŽ€ Socket-layer functions ๐ŸŽ€

These are the functions your user process uses to send and receive packets and do all the other cute socket operations. Each one has its own manual page, so go peek at those for the deep dive. โœจ

  • socket(2) โ€” creates a socket ๐Ÿฃ
  • connect(2) โ€” connects a socket to a remote socket address ๐Ÿ”—
  • bind(2) โ€” binds a socket to a local socket address ๐Ÿ“
  • listen(2) โ€” tells the socket that new connections shall be accepted ๐Ÿ‘‚
  • accept(2) โ€” gets you a shiny new socket with a new incoming connection ๐ŸŽ
  • socketpair(2) โ€” returns two connected anonymous sockets (and heads up, this is implemented only for a few local families like** AF_UNIX**)

send(2), sendto(2), and sendmsg(2) send data over a socket, while recv(2), recvfrom(2), and recvmsg(2) receive data from a socket. ๐Ÿ“จ Then poll(2) and select(2) just vibe and wait for arriving data or for readiness to send data. Plus the standard I/O operations โ€” write(2), writev(2), sendfile(2), read(2), and readv(2) โ€” can all be used to read and write data too. No gatekeeping here.

getsockname(2) returns the local socket address and getpeername(2) returns the remote socket address. getsockopt(2) and setsockopt(2) are your get/set duo for socket layer or protocol options. And ioctl(2) can be used to set or read some other options. ๐Ÿ› ๏ธ

close(2) closes a socket. shutdown(2) closes parts of a full-duplex socket connection. โœ‚๏ธ

Seeking, or calling pread(2) or pwrite(2) with a nonzero position, is not supported on sockets. Don't try it, it's not giving.

Nonblocking I/O on sockets is a whole thing and it's easy: set the O_NONBLOCK flag on a socket file descriptor using fcntl(2). After that, every operation that would block will (usually) return with EAGAIN โ€” which is basically the kernel saying "retry later bestie" โ€” and connect(2) will return the EINPROGRESS error instead. Then you can go wait for whatever events you care about via poll(2) or select(2). ๐Ÿ’ค

Here's the iconic I/O events chart, table-ified for your reading pleasure:

  • Read โ€” poll flag POLLIN โ€” New data arrived. ๐Ÿ“ฅ
  • Read โ€” poll flag POLLIN โ€” A connection setup has been completed (for connection-oriented sockets).
  • Read โ€” poll flag POLLHUP โ€” A disconnection request has been initiated by the other end.
  • Read โ€” poll flag POLLHUP โ€” A connection is broken (only for connection-oriented protocols). When the socket is written SIGPIPE is also sent. ๐Ÿ’€
  • Write โ€” poll flag POLLOUT โ€” Socket has enough send buffer space for writing new data. ๐Ÿ“ค
  • Read/Write โ€” poll flag POLLIN | POLLOUT โ€” An outgoing connect(2) finished.
  • Read/Write โ€” poll flag POLLERR โ€” An asynchronous error occurred.
  • Read/Write โ€” poll flag POLLHUP โ€” The other end has shut down one direction.
  • Exception โ€” poll flag POLLPRI โ€” Urgent data arrived. SIGURG is sent then. ๐Ÿšจ

An alternative to poll(2) and select(2)? Let the kernel text you about events instead, via a SIGIO signal. ๐Ÿ“ฑ For that, the O_ASYNC flag must be set on a socket file descriptor via fcntl(2), and a valid signal handler for SIGIO must be installed via sigaction(2). There's a whole Signals discussion further down this page, so hold that thought.


๐Ÿฆ‹ Socket address structures ๐Ÿฆ‹

Every socket domain has its own format for socket addresses, with a domain-specific address structure. And every one of those structures begins with an integer "family" field (typed as sa_family_t) that says which type of address structure it is. That's how the generic system calls โ€” like connect(2), bind(2), accept(2), getsockname(2), getpeername(2) โ€” figure out the domain of a particular socket address. Clever, right? ๐Ÿ’ก

To let any type of socket address get passed to interfaces in the sockets API, the type struct sockaddr is defined. Its purpose is purely to allow casting domain-specific socket address types to a "generic" type โ€” so you dodge those compiler warnings about type mismatches in calls to the sockets API. It's a costume, not a real identity. ๐Ÿ‘‘

On top of that, the sockets API gives you the data type struct sockaddr_storage. This one is suitable for accommodating all supported domain-specific socket address structures โ€” it's large enough and it's aligned properly. (In particular, it's large enough to hold IPv6 socket addresses. ๐Ÿ‘‘โœจ) The structure includes this field, which you can use to identify which type of socket address is actually stored inside:

sa_family_t ss_family;

struct sockaddr_storage is useful in programs that have to handle socket addresses in a generic way โ€” like programs dealing with both IPv4 and IPv6 socket addresses at the same time. ๐ŸŒ


๐Ÿ’… Socket options ๐Ÿ’…

All the socket options below can be set with setsockopt(2) and read with getsockopt(2), with the socket level set to SOL_SOCKET for all sockets. And unless it says otherwise, optval is a pointer to an int. ๐Ÿ“Œ

  • SO_ACCEPTCONN โ€” Returns a value indicating whether or not this socket has been marked to accept connections with listen(2). The value 0 means this is not a listening socket, and the value 1 means this is a listening socket. This socket option is read-only, so don't even try to set it. ๐Ÿ™…
  • SO_ATTACH_FILTER (since Linux 2.2) โ€” and its sibling SO_ATTACH_BPF (since Linux 3.19) โ€” Attach a classic BPF (SO_ATTACH_FILTER) or an extended BPF (SO_ATTACH_BPF) program to the socket, to be used as a filter of incoming packets. ๐Ÿงผ A packet gets dropped if the filter program returns zero. If the filter program returns a nonzero value that is less than the packet's data size, the packet will be truncated to the size returned. And if the value returned by the filter is greater than or equal to the packet's data size, the packet is allowed to proceed unmodified. โœจ

The argument for SO_ATTACH_FILTER is a sock_fprog structure, defined in <linux/filter.h>:

struct sock_fprog {
    unsigned short      len;
    struct sock_filter *filter;
};

The argument for SO_ATTACH_BPF is a file descriptor returned by the bpf(2) system call, and it must refer to a program of type BPF_PROG_TYPE_SOCKET_FILTER.

These options may be set multiple times for a given socket, each time replacing the previous filter program. The classic and extended versions may be called on the same socket, but the previous filter will always be replaced, so a socket never has more than one filter defined. One filter, one vibe. ๐ŸŽฏ

Both classic and extended BPF are explained in the kernel source file Documentation/networking/filter.rst โ€” go read it if you want the full dissertation, iykyk. ๐Ÿ“–

  • SO_ATTACH_REUSEPORT_CBPF โ€” and SO_ATTACH_REUSEPORT_EBPF โ€” For use with the SO_REUSEPORT option, these options let the user set a classic BPF (SO_ATTACH_REUSEPORT_CBPF) or an extended BPF (SO_ATTACH_REUSEPORT_EBPF) program which defines how packets are assigned to the sockets in the reuseport group โ€” that is, all sockets which have SO_REUSEPORT set and are using the same local address to receive packets. ๐ŸŽช

The classic BPF program must return an index between 0 and N-1, representing the socket which should receive the packet (where N is the number of sockets in the group). And if the BPF program returns an invalid index, socket selection will fall back to the plain SO_REUSEPORT mechanism. ๐Ÿ”„


more coming in part 2, don't go anywhere bestie ๐Ÿ’–

Okay so the way this works ๐ŸŒ€ sockets get numbered in the order they're added to the group (that is, the order of bind(2) calls for UDP sockets, or the order of listen(2) calls for TCP sockets). Very demure, very orderly.

Your extended BPF program can come in two flavors, bestie:

  • BPF_PROG_TYPE_SOCKET_FILTER โ€” in this case, the extended BPF program must return an index between 0 and N-1, exactly like a classic BPF program does.
  • BPF_PROG_TYPE_SK_REUSEPORT (since Linux 4.19) โ€” in this case, it must return an action (SK_PASS or SK_DROP), and the bpf_sk_select_reuseport helper can be used to select the socket that should receive the packet. Very choose-your-own-adventure โœจ

New sockets added to a reuseport group will inherit the BPF program. And when a socket is removed from a reuseport group (via close(2)), the last socket in the group gets moved into the closed socket's position. No gaps, no drama ๐Ÿ’…

These options may be set repeatedly at any time on any socket in the group, to replace the current BPF program used by all the sockets in the group.

SO_ATTACH_REUSEPORT_CBPF takes the same argument type as SO_ATTACH_FILTER, and SO_ATTACH_REUSEPORT_EBPF takes the same argument type as SO_ATTACH_BPF.

UDP support for this feature is available since Linux 4.5; TCP support is available since Linux 4.6. ๐Ÿ“…


๐Ÿฆ‹ SO_BINDTODEVICE

Bind this socket to one particular device, like <pink>โ€œeth0โ€</pink>, as specified in the interface name you pass in. If the name is an empty string, or the option size is zero, the socket's device binding gets removed. The option you pass is a variable-size, null-terminated interface name string, and its maximum size is IFNAMSIZ. Once a socket is bound to an interface, only packets received from that particular interface get processed by the socket.

Heads up ๐Ÿซถ this only works for some socket types, particularly AF_INET sockets. And it is not supported for packet sockets (use a normal bind(2) over there instead).

Before Linux 3.8, this socket option could be set but could not be retrieved with getsockopt(2). Since Linux 3.8, it is readable. The optlen argument should contain the buffer size available to receive the device name, and it is recommended to be IFNAMSIZ bytes. The real device name length is reported back in the optlen argument.

๐ŸŽ€ SO_BROADCAST

Set or get the broadcast flag. When it's enabled, datagram sockets are allowed to send packets to a broadcast address. This option has no effect on stream-oriented sockets.

๐Ÿ’€ SO_BSDCOMPAT

Enable BSD bug-to-bug compatibility. Yes bestie, that's literally what it's called, and it's giving ancient lore. This is used by the UDP protocol module in Linux 2.0 and 2.2. If enabled, ICMP errors received for a UDP socket will not be passed to the user program.

In later kernel versions, support for this option has been phased out: Linux 2.4 silently ignores it, and Linux 2.6 generates a kernel warning (printk()) if a program uses this option. Linux 2.0 also enabled BSD bug-to-bug compatibility options (random header changing, skipping of the broadcast flag) for raw sockets with this option, but that was removed in Linux 2.2. Soโ€ฆ rest in peace, king ๐Ÿชฆ

๐Ÿ”’ SO_DEBUG

Enable socket debugging. Allowed only for processes with the CAP_NET_ADMIN capability, or an effective user ID of 0. So if that's not youโ€ฆ yeah, sorry ๐Ÿ˜ญ

SO_DETACH_FILTER (since Linux 2.2), SO_DETACH_BPF (since Linux 3.19)

These two options, which are synonyms, may be used to remove the classic or extended BPF program attached to a socket with either SO_ATTACH_FILTER or SO_ATTACH_BPF. The option value is ignored. Filter, you are dismissed ๐Ÿ’จ

๐ŸŒˆ SO_DOMAIN (since Linux 2.6.32)

Retrieves the socket domain as an integer, returning a value such as AF_INET6. See socket(2) for the details. This socket option is read-only.

โญ SO_ERROR

Get and clear the pending socket error. This socket option is read-only. Expects an integer.

๐ŸŒธ SO_DONTROUTE

Don't send via a gateway โ€” send only to directly connected hosts. You can get the exact same effect by setting the MSG_DONTROUTE flag on a socket send(2) operation. Expects an integer boolean flag.

๐Ÿงš SO_INCOMING_CPU (gettable since Linux 3.19, settable since Linux 4.4)

Sets or gets the CPU affinity of a socket. Expects an integer flag.

int cpu = 1;
setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu,
           sizeof(cpu));

Because all of the packets for a single stream (i.e., all packets for the same 4-tuple) arrive on the single RX queue that is associated with a particular CPU, the typical use case is to employ one listening process per RX queue, with the incoming flow being handled by a listener on the same CPU that is handling the RX queue. This provides optimal NUMA behavior and keeps CPU caches hot. ๐Ÿ”ฅ Peak performance behavior, honestly.

๐Ÿซถ SO_INCOMING_NAPI_ID (gettable since Linux 4.12)

Returns a system-level unique ID called NAPI ID that is associated with a RX queue on which the last packet associated with that socket is received.

This can be used by an application to split the incoming flows among worker threads based on the RX queue on which the packets associated with the flows are received. It allows each worker thread to be associated with a NIC HW receive queue and service all the connection requests received on that RX queue. This mapping between an app thread and a HW NIC queue streamlines the flow of data from the NIC to the application. Chef's kiss ๐Ÿง‘โ€๐Ÿณ

๐Ÿ’– SO_KEEPALIVE

Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag. Keeping the relationship alive, fr fr.

SO_LINGER

Sets or gets the SO_LINGER option. The argument is a linger structure.

struct linger {
    int l_onoff;    /* linger active */
    int l_linger;   /* how many seconds to linger for */
};

When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent, or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of _exit(3), it always lingers in the background.

๐Ÿ” SO_LOCK_FILTER

When set, this option will prevent changing the filters associated with the socket. These filters include any set using the socket options SO_ATTACH_FILTER, SO_ATTACH_BPF, SO_ATTACH_REUSEPORT_CBPF, and SO_ATTACH_REUSEPORT_EBPF.

The typical use case is for a privileged process to set up a raw socket (an operation that requires the CAP_NET_RAW capability), apply a restrictive filter, set the SO_LOCK_FILTER option, and then either drop its privileges or pass the socket file descriptor to an unprivileged process via a UNIX domain socket. Lock it down and the vibes are immaculate ๐Ÿ‘‘

Once the SO_LOCK_FILTER option has been enabled, attempts to change or remove the filter attached to a socket, or to disable the SO_LOCK_FILTER option, will fail with the error EPERM.

โญ SO_MARK (since Linux 2.6.25)

Set the mark for each packet sent through this socket (similar to the netfilter MARK target, but socket-based). Changing the mark can be used for mark-based routing without netfilter, or for packet filtering. Setting this option requires the CAP_NET_ADMIN or CAP_NET_RAW (since Linux 5.17) capability.

๐ŸŽ€ SO_OOBINLINE

If this option is enabled, out-of-band data is directly placed into the receive data stream. Otherwise, out-of-band data is passed only when the MSG_OOB flag is set during receiving.

๐Ÿ’œ SO_PASSCRED

Enable or disable the receiving of the SCM_CREDENTIALS control message. For more information, see unix(7).

๐Ÿ’œ SO_PASSSEC

Enable or disable the receiving of the SCM_SECURITY control message. For more information, see unix(7).

๐Ÿ“ SO_PEEK_OFF (since Linux 3.4)

This option โ€” currently supported only for unix(7) sockets โ€” sets the value of the "peek offset" for the recv(2) system call when it's used with the MSG_PEEK flag.

When this option is set to a negative value (it is set to -1 for all new sockets), traditional behavior is provided: recv(2) with the MSG_PEEK flag will peek data from the front of the queue.

When the option is set to a value greater than or equal to zero, then the next peek at data queued in the socket will occur at the byte offset specified by the option value. At the same time, the "peek offset" will be incremented by the number of bytes that were peeked from the queue, so that a subsequent peek will return the next data in the queue.

If data is removed from the front of the queue via a call to recv(2) (or similar) without the MSG_PEEK flag, the "peek offset" will be decreased by the number of bytes removed. In other words, receiving data without the MSG_PEEK flag will cause the "peek offset" to be adjusted to maintain the correct relative position in the queued data, so that a subsequent peek will retrieve the data that would have been retrieved had the data not been removed. The offset stays in its lane, basically โœจ

For datagram sockets, if the "peek offset" points to the middle of a packet, the data returned will be marked with the MSG_TRUNC flag.

The following example serves to illustrate the use of SO_PEEK_OFF. Suppose a stream socket has the following queued input data:

aabbccddeeff

The following sequence of recv(2) calls would have the effect noted in the comments:

int ov = 4;                  // Set peek offset to 4
setsockopt(fd, SOL_SOCKET, SO_PEEK_OFF, &ov, sizeof(ov));

recv(fd, buf, 2, MSG_PEEK);  // Peeks "cc"; offset set to 6
recv(fd, buf, 2, MSG_PEEK);  // Peeks "dd"; offset set to 8
recv(fd, buf, 2, 0);         // Reads "aa"; offset set to 6
recv(fd, buf, 2, MSG_PEEK);  // Peeks "ee"; offset set to 8

๐Ÿฆ‹ SO_PEERCRED

Return the credentials of the peer process connected to this socket. For further details, see unix(7).

SO_PEERSEC(2const)

(and that's literally all this page has for it, bestie)

  • SO_PRIORITY โ€” sets the protocol-defined priority for every packet this socket sends out ๐Ÿ’Œ. Linux uses this number to order its networking queues, and depending on the device queueing discipline you're riding with, higher-priority packets may get processed first. Fair warning bestie: setting a priority outside the range 0 to 6 needs the CAP_NET_ADMIN capability, so plebs cannot ๐Ÿ’€.
  • SO_PROTOCOL (since Linux 2.6.32) โ€” retrieves the socket protocol as an integer, handing you back something like IPPROTO_SCTP. Full details live in socket(2). Heads up: this socket option is read-only ๐ŸŒธ.
  • SO_RCVBUF โ€” sets or gets the max socket receive buffer in bytes. The kernel doubles this value when you set it with setsockopt(2) (so there's room for bookkeeping overhead), and that doubled value is what getsockopt(2) gives back to you โ€” so don't be shocked when the number looks thiccc ๐Ÿซถ. The default comes from the /proc/sys/net/core/rmem_default file, the maximum allowed value comes from /proc/sys/net/core/rmem_max, and the minimum (doubled) value for this option is 256.
  • SO_RCVBUFFORCE (since Linux 2.6.14) โ€” if you're a privileged (CAP_NET_ADMIN) process, this does the exact same thing as SO_RCVBUF, except you get to override the rmem_max limit. Main character energy only ๐Ÿ‘‘.
  • SO_RCVLOWAT, SO_SNDLOWAT โ€” these two set the minimum number of bytes that have to be sitting in the buffer before the socket layer hands data over to the protocol (SO_SNDLOWAT) or to the user on receiving (SO_RCVLOWAT). Both start out initialized to 1. Important tea: SO_SNDLOWAT is not changeable on Linux โ€” setsockopt(2) fails with the error ENOPROTOOPT โ€” and SO_RCVLOWAT has only been changeable since Linux 2.4.

Flashback moment ๐Ÿ“ผ: before Linux 2.6.28, select(2), poll(2), and epoll(7) on Linux flat-out ignored the SO_RCVLOWAT setting and would call a socket readable when even a single byte of data was available. Then your subsequent read would block anyway until SO_RCVLOWAT bytes showed up. Rude. Since Linux 2.6.28 they behave, and a socket is only flagged readable if at least SO_RCVLOWAT bytes are actually there โœจ.

  • SO_RCVTIMEO, SO_SNDTIMEO โ€” the receiving or sending timeouts, counting down until an error gets reported โฐ. The argument is a struct timeval. If an input or output function blocks for that long and data has been sent or received, the return value of that function is the amount of data transferred. If no data moved at all and the timeout hit, then -1 comes back with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) โ€” exactly as if the socket was set to nonblocking. If the timeout is set to zero (the default), the operation will never timeout. And these timeouts only hit system calls that actually do socket I/O (like accept(2), connect(2), read(2), recvmsg(2), send(2), sendmsg(2)) โ€” they do nothing for select(2), poll(2), epoll_wait(2), and friends, iykyk ๐Ÿ’….
  • SO_REUSEADDR โ€” tells the address-validation rules used by bind(2) that it's fine to reuse local addresses ๐Ÿ”. For AF_INET sockets that means a socket may bind, except when there's an active listening socket already bound to the address. And when a listening socket is bound to INADDR_ANY with a specific port, then binding to that port for any local address is just not happening, sorry babe. The argument is an integer boolean flag.
  • SO_REUSEPORT (since Linux 3.9) โ€” lets multiple AF_INET or AF_INET6 sockets bind to an identical socket address ๐ŸŽ€. You must set this option on each socket (yes, including the very first one) before calling bind(2). To prevent port hijacking, all the processes binding to the same address have to share the same effective UID. Works with both TCP and UDP sockets.

For TCP sockets: this enables accept(2) load distribution in a multi-threaded server, letting you use a distinct listener socket per thread ๐Ÿ”ฅ. That's better load distribution than the old-school techniques โ€” like having a single accept(2)ing thread that hands out connections, or having a bunch of threads fight over accept(2) on the same socket (chaos, honestly).

For UDP sockets: this gives better distribution of incoming datagrams to multiple processes (or threads) compared to the traditional technique where multiple processes compete to receive datagrams on the same socket ๐Ÿ˜ค.

  • SO_RXQ_OVFL (since Linux 2.6.33) โ€” says that an unsigned 32-bit value ancillary message (cmsg) should be attached to received skbs, reporting the number of packets the socket has dropped since it was created ๐Ÿ“‰.
  • SO_SELECT_ERR_QUEUE (since Linux 3.10) โ€” when you set this on a socket, an error condition on that socket gets you a notification not only through the exceptfds set of select(2). Likewise, poll(2) also returns a POLLPRI whenever a POLLERR event is returned ๐Ÿšจ.

The lore ๐Ÿ“–: this option got added back when waking up on an error condition only happened via the readfds and writefds sets of select(2). It was there so you could monitor for error conditions through the exceptfds argument without having to simultaneously get notifications (via readfds) for regular data that's readable on the socket. But after changes in Linux 4.16, using this flag to get the notifications you want is no longer necessary. It's still hanging around for backwards compatibility, a true veteran ๐Ÿซก.

  • SO_SNDBUF โ€” sets or gets the max socket send buffer in bytes. Same deal as its receive sibling: the kernel doubles the value when it's set using setsockopt(2), and that doubled value is what getsockopt(2) returns. The default comes from the /proc/sys/net/core/wmem_default file and the maximum allowed is set by the /proc/sys/net/core/wmem_max file. The minimum (doubled) value for this option is 2048.
  • SO_SNDBUFFORCE (since Linux 2.6.14) โ€” for privileged (CAP_NET_ADMIN) processes, this does the same task as SO_SNDBUF, but the wmem_max limit can be overridden ๐Ÿ’ฅ.
  • SO_TIMESTAMP โ€” enables or disables receiving the SO_TIMESTAMP control message ๐Ÿ•. That timestamp control message shows up with level SOL_SOCKET and a cmsg_type of SCM_TIMESTAMP; the cmsg_data field is a struct timeval indicating the reception time of the last packet passed to the user in this call. Peep cmsg(3) for the deets on control messages.
  • SO_TIMESTAMPNS (since Linux 2.6.22) โ€” enables or disables receiving the SO_TIMESTAMPNS control message โฑ๏ธ. This one arrives with level SOL_SOCKET and a cmsg_type of SCM_TIMESTAMPNS, and its cmsg_data field is a struct timespec indicating the reception time of the last packet passed to the user in this call. The clock used for the timestamp is CLOCK_REALTIME. Again, cmsg(3) has the full story.
Major note bestie: a socket cannot mix SO_TIMESTAMP and SO_TIMESTAMPNS โ€” the two modes are mutually exclusive, pick one and commit ๐Ÿšซ.
  • SO_TYPE โ€” gets the socket type as an integer (e.g., SOCK_STREAM). This socket option is read-only ๐Ÿ™ˆ.
  • SO_BUSY_POLL (since Linux 3.11) โ€” sets the approximate time in microseconds to busy poll on a blocking receive when there's no data. Increasing this value requires CAP_NET_ADMIN. The default for this option is controlled by the /proc/sys/net/core/busy_read file.

Meanwhile, the value in the /proc/sys/net/core/busy_poll file decides how long select(2) and poll(2) will busy poll when they're operating on sockets with SO_BUSY_POLL set and no events to report turn up.

In both cases, busy polling only happens when the socket last received data from a network device that supports this option ๐Ÿ›ฐ๏ธ.

Real talk: while busy polling may improve latency for some applications, be careful with it โ€” it increases both CPU utilization and power usage ๐Ÿ”‹. Your laptop fan will not thank you.

๐Ÿฆ‹ Signals ๐Ÿฆ‹

When you write onto a connection-oriented socket that's already been shut down (by the local end or the remote end), SIGPIPE gets sent to the writing process and EPIPE is returned ๐Ÿ’”. That signal does not get sent if the write call specified the MSG_NOSIGNAL flag.

When it's requested with the FIOSETOWN fcntl(2) or SIOCSPGRP ioctl(2), SIGIO is sent whenever an I/O event occurs ๐Ÿ“ฃ. You can use poll(2) or select(2) inside the signal handler to figure out which socket the event happened on. An alternative (in Linux 2.2) is setting a real-time signal using the F_SETSIG fcntl(2) โ€” the real-time signal's handler then gets called with the file descriptor in the si_fd field of its siginfo_t. fcntl(2) has more info โœจ.

Under some circumstances (like multiple processes accessing a single socket, messy), the condition that caused the SIGIO may have already disappeared by the time the process reacts to the signal ๐Ÿ‘ป. If that happens, the process should just wait again, because Linux will resend the signal later. It's not ghosting you, just running late.


๐ŸŒˆ /proc interfaces ๐ŸŒˆ

The core socket networking parameters can be accessed via files in the directory /proc/sys/net/core/ ๐Ÿ“.

  • rmem_default โ€” contains the default setting in bytes of the socket receive buffer ๐Ÿ’–.
  • rmem_max โ€” contains the maximum socket receive buffer size in bytes which a user may set using the SO_RCVBUF socket option.
  • wmem_default โ€” contains the default setting in bytes of the socket send buffer ๐Ÿ“ค.
  • wmem_max โ€” contains the maximum socket send buffer size in bytes which a user may set using the SO_SNDBUF socket option.
  • message_cost, message_burst โ€” configure the token bucket filter used to load limit warning messages caused by external network events ๐Ÿชฃ.
  • netdev_max_backlog โ€” the maximum number of packets in the global input queue ๐Ÿ“ฆ.
  • optmem_max โ€” the maximum size of ancillary data and user control data like the iovecs per socket.

๐Ÿ’… Ioctls ๐Ÿ’…

These operations can be accessed using ioctl(2):

error = ioctl(ip_socket, ioctl_type, &value_result);
  • SIOCGSTAMP โ€” hands you back a struct timeval stuffed with the receive timestamp of the last packet that got passed up to userspace. super useful for accurate round-trip-time measurements, bestie. Wanna know what a struct timeval even is? Go read setitimer(2), it explains it. โš ๏ธ Big important thing: only use this ioctl if SO_TIMESTAMP and SO_TIMESTAMPNS are not set on the socket. Otherwise it gives you the timestamp of the last packet that arrived while SO_TIMESTAMP and SO_TIMESTAMPNS were not set โ€” or it just flat-out fails if no such packet ever came in, i.e. ioctl(2) returns -1 with errno set to ENOENT. no packet, no timestamp, periodt ๐Ÿ˜ญ
  • SIOCSPGRP โ€” picks who gets to receive the SIGIO or SIGURG signals when I/O becomes possible or when urgent data shows up. Could be a process, could be a whole process group โ€” your call โœจ. The argument is a pointer to a pid_t. Want the deep lore? It's all in the description of F_SETOWN in fcntl(2). ๐Ÿซถ
  • FIOASYNC โ€” flips the O_ASYNC flag to turn asynchronous I/O mode on or off for the socket. Asynchronous I/O mode = the SIGIO signal, or whatever signal you set with F_SETSIG, gets raised the moment a new I/O event happens. ๐Ÿ‘‘

The argument is an integer boolean flag. Fun fact: this operation is literally synonymous with using fcntl(2) to set the O_ASYNC flag. Same vibe, different door ๐Ÿšชโœจ

  • SIOCGPGRP โ€” tells you the current process or process group that's receiving SIGIO or SIGURG signals, or 0 when nothing is set. simple, clean, informative.

โœจ Valid fcntl(2) operations โœจ

  • FIOGETOWN โ€” the exact same thing as the SIOCGPGRP ioctl(2). ๐Ÿ’…
  • FIOSETOWN โ€” the exact same thing as the SIOCSPGRP ioctl(2). ๐ŸŒธ

๐ŸŒˆ VERSIONS ๐ŸŒˆ

Okay so here's the timeline, bestie, let's get chronological:

  • SO_BINDTODEVICE dropped in Linux 2.0.30.
  • SO_PASSCRED is new in Linux 2.2.
  • The /proc interfaces arrived in Linux 2.2.
  • SO_RCVTIMEO and SO_SNDTIMEO have been supported since Linux 2.3.41.

And before that? ๐Ÿ˜ญ Timeouts were just fixed to a protocol-specific setting โ€” you could not read them and you could not write them. Tragic. No cap.


๐ŸŽ€ NOTES ๐ŸŽ€

Linux assumes that half of the send/receive buffer is used for internal kernel structures โ€” which means the values you see in the corresponding /proc files are twice what you'd actually observe on the wire. Yes, double. Not a bug, just the vibes. ๐Ÿ”ฅ

And about port reuse: Linux will allow port reuse with the SO_REUSEADDR option only when that option was set both in the previous program that did a bind(2) to the port and in the program that wants to reuse the port. This is lowkey different from some other implementations (looking at you, FreeBSD ๐Ÿ‘€) where only the later program needs to set SO_REUSEADDR. Most of the time you'll never notice the difference though, since โ€” for example โ€” a server program is designed to always set this option anyway. invisible difference, iconic energy โœจ


๐Ÿ’– SEE ALSO ๐Ÿ’–

wireshark(1), bpf(2), connect(2), getsockopt(2), setsockopt(2), socket(2), pcap(3), address_families(7), capabilities(7), ddp(7), ip(7), ipv6(7), packet(7), tcp(7), udp(7), unix(7), tcpdump(8)


And that's the whole page, bestie!! ๐Ÿฆ‹ This lil masterpiece comes from Linux man-pages 6.20, dated 2026-06-05, and the page is socket(7). Go forth and slay your sockets ๐Ÿ’…๐Ÿงš๐Ÿ’œ

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: Linux-man-pages-1-para
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms