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 callingpread(2)orpwrite(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 writtenSIGPIPEis also sent. ๐ - Write โ poll flag
POLLOUTโ Socket has enough send buffer space for writing new data. ๐ค - Read/Write โ poll flag
POLLIN | POLLOUTโ An outgoingconnect(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.SIGURGis 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 withlisten(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 siblingSO_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โ andSO_ATTACH_REUSEPORT_EBPFโ For use with theSO_REUSEPORToption, 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 haveSO_REUSEPORTset 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_PASSorSK_DROP), and thebpf_sk_select_reuseporthelper 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, particularlyAF_INETsockets. And it is not supported for packet sockets (use a normalbind(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 range0to6needs theCAP_NET_ADMINcapability, so plebs cannot ๐.SO_PROTOCOL(since Linux 2.6.32) โ retrieves the socket protocol as an integer, handing you back something likeIPPROTO_SCTP. Full details live insocket(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 withsetsockopt(2)(so there's room for bookkeeping overhead), and that doubled value is whatgetsockopt(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_defaultfile, the maximum allowed value comes from/proc/sys/net/core/rmem_max, and the minimum (doubled) value for this option is256.SO_RCVBUFFORCE(since Linux 2.6.14) โ if you're a privileged (CAP_NET_ADMIN) process, this does the exact same thing asSO_RCVBUF, except you get to override thermem_maxlimit. 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 to1. Important tea:SO_SNDLOWATis not changeable on Linux โsetsockopt(2)fails with the errorENOPROTOOPTโ andSO_RCVLOWAThas 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 astruct 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-1comes back witherrnoset toEAGAINorEWOULDBLOCK, orEINPROGRESS(forconnect(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 (likeaccept(2),connect(2),read(2),recvmsg(2),send(2),sendmsg(2)) โ they do nothing forselect(2),poll(2),epoll_wait(2), and friends, iykyk ๐ .SO_REUSEADDRโ tells the address-validation rules used bybind(2)that it's fine to reuse local addresses ๐. ForAF_INETsockets 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 toINADDR_ANYwith 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 multipleAF_INETorAF_INET6sockets bind to an identical socket address ๐. You must set this option on each socket (yes, including the very first one) before callingbind(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 theexceptfdsset ofselect(2). Likewise,poll(2)also returns aPOLLPRIwhenever aPOLLERRevent 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 usingsetsockopt(2), and that doubled value is whatgetsockopt(2)returns. The default comes from the/proc/sys/net/core/wmem_defaultfile and the maximum allowed is set by the/proc/sys/net/core/wmem_maxfile. The minimum (doubled) value for this option is2048.SO_SNDBUFFORCE(since Linux 2.6.14) โ for privileged (CAP_NET_ADMIN) processes, this does the same task asSO_SNDBUF, but thewmem_maxlimit can be overridden ๐ฅ.SO_TIMESTAMPโ enables or disables receiving theSO_TIMESTAMPcontrol message ๐. That timestamp control message shows up with levelSOL_SOCKETand acmsg_typeofSCM_TIMESTAMP; thecmsg_datafield is astruct timevalindicating the reception time of the last packet passed to the user in this call. Peepcmsg(3)for the deets on control messages.SO_TIMESTAMPNS(since Linux 2.6.22) โ enables or disables receiving theSO_TIMESTAMPNScontrol message โฑ๏ธ. This one arrives with levelSOL_SOCKETand acmsg_typeofSCM_TIMESTAMPNS, and itscmsg_datafield is astruct timespecindicating the reception time of the last packet passed to the user in this call. The clock used for the timestamp isCLOCK_REALTIME. Again,cmsg(3)has the full story.
Major note bestie: a socket cannot mixSO_TIMESTAMPandSO_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 requiresCAP_NET_ADMIN. The default for this option is controlled by the/proc/sys/net/core/busy_readfile.
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 theSO_RCVBUFsocket 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 theSO_SNDBUFsocket 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 theiovecsper socket.
๐ Ioctls ๐
These operations can be accessed using ioctl(2):
error = ioctl(ip_socket, ioctl_type, &value_result);
SIOCGSTAMPโ hands you back astruct timevalstuffed 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 astruct timevaleven is? Go readsetitimer(2), it explains it. โ ๏ธ Big important thing: only use this ioctl ifSO_TIMESTAMPandSO_TIMESTAMPNSare not set on the socket. Otherwise it gives you the timestamp of the last packet that arrived whileSO_TIMESTAMPandSO_TIMESTAMPNSwere not set โ or it just flat-out fails if no such packet ever came in, i.e.ioctl(2)returns-1witherrnoset toENOENT. no packet, no timestamp, periodt ๐ญSIOCSPGRPโ picks who gets to receive theSIGIOorSIGURGsignals 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 apid_t. Want the deep lore? It's all in the description ofF_SETOWNinfcntl(2). ๐ซถFIOASYNCโ flips theO_ASYNCflag to turn asynchronous I/O mode on or off for the socket. Asynchronous I/O mode = theSIGIOsignal, or whatever signal you set withF_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 receivingSIGIOorSIGURGsignals, or0when nothing is set. simple, clean, informative.
โจ Valid fcntl(2) operations โจ
FIOGETOWNโ the exact same thing as theSIOCGPGRPioctl(2). ๐FIOSETOWNโ the exact same thing as theSIOCSPGRPioctl(2). ๐ธ
๐ VERSIONS ๐
Okay so here's the timeline, bestie, let's get chronological:
SO_BINDTODEVICEdropped in Linux 2.0.30.SO_PASSCREDis new in Linux 2.2.- The
/procinterfaces arrived in Linux 2.2. SO_RCVTIMEOandSO_SNDTIMEOhave 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
- Copyright 1999, Andi Kleen <andi@firstfloor.org>
- Copyright 1999, Matthew Wilcox <willy@bofh.ai>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms