Socket Module

The socket module provides functions for interacting with sockets.

Functions can be individually imported and directly accessed using the named import syntax:

import { AF_INET, SOCK_STREAM, create as socket } from 'socket';

let sock = socket(AF_INET, SOCK_STREAM, 0);
sock.connect('192.168.1.1', 80);
sock.send(…);
sock.recv(…);
sock.close();

Alternatively, the module namespace can be imported using a wildcard import statement:

import * as socket from 'socket';

let sock = socket.create(socket.AF_INET, socket.SOCK_STREAM, 0);
sock.connect('192.168.1.1', 80);
sock.send(…);
sock.recv(…);
sock.close();

Additionally, the socket module namespace may also be imported by invoking the ucode interpreter with the -lsocket switch.

Classes

socket.socket

Represents a socket handle.

Methods

addrinfo(hostname, serviceopt, hintsopt) → {AddressInfo[]}nullable

Resolves the given hostname and optional service name into a list of network addresses, according to the provided hints.

The addrinfo() function provides an API for performing DNS and service name resolution. It returns an array of objects, each representing a resolved address.

Returns an array of resolved addresses. Returns null if an error occurred during resolution.

Parameters:
NameTypeDescription
hostnamestring

The hostname to resolve.

servicestring(optional)

Optional service name to resolve. If not provided, the service field of the resulting address information structures is left uninitialized.

hintsObject(optional)

Optional hints object that provides additional control over the resolution process. It can contain the following properties:

  • family: The preferred address family (AF_INET or AF_INET6).
  • socktype: The socket type (SOCK_STREAM, SOCK_DGRAM, etc.).
  • protocol: The protocol of returned addresses.
  • flags: Bitwise OR-ed AI_* flags to control the resolution behavior.
Returns: AddressInfo[]
Example
// Resolve all addresses
const addresses = socket.addrinfo('example.org');

// Resolve IPv4 addresses for a given hostname and service
const ipv4addresses = socket.addrinfo('example.com', 'http', { family: socket.AF_INET });

// Resolve IPv6 addresses without specifying a service
const ipv6Addresses = socket.addrinfo('example.com', null, { family: socket.AF_INET6 });
See
  • Socket Types
  • Address Info Flags

connect(host, serviceopt, hintsopt, timeoutopt) → {socket}

Creates a network socket and connects it to the specified host and service.

This high level function combines the functionality of create(), addrinfo() and connect() to simplify connection establishment with the socket module.

Parameters:
NameTypeDescription
hoststring | number[] | socket.SocketAddress

The host to connect to, can be an IP address, hostname, SocketAddress, or an array value returned by iptoarr().

servicestring | number(optional)

The service to connect to, can be a symbolic service name (such as "http") or a port number. Optional if host is specified as SocketAddress.

hintsObject(optional)

Optional preferences for the socket. It can contain the following properties:

  • family: The preferred address family (AF_INET or AF_INET6).
  • socktype: The socket type (SOCK_STREAM, SOCK_DGRAM, etc.).
  • protocol: The protocol of the created socket.
  • flags: Bitwise OR-ed AI_* flags to control the resolution behavior.

If no hints are not provided, the default socket type preference is set to SOCK_STREAM.

timeoutnumber(optional, default: -1)

The timeout in milliseconds for socket connect operations. If set to a negative value, no specifc time limit is imposed and the function will block until either a connection was successfull or the underlying operating system timeout is reached.

Returns: socket
Example
// Resolve host, try to connect to both resulting IPv4 and IPv6 addresses
let conn = socket.connect("example.org", 80);

// Enforce usage of IPv6
let conn = socket.connect("example.com", 80, { family: socket.AF_INET6 });

// Connect a UDP socket
let conn = socket.connect("192.168.1.1", 53, { socktype: socket.SOCK_DGRAM });

// Bypass name resolution by specifying a SocketAddress structure
let conn = socket.connect({ address: "127.0.0.1", port: 9000 });

// Use SocketAddress structure to connect a UNIX domain socket
let conn = socket.connect({ path: "/var/run/daemon.sock" });

create(domainopt, typeopt, protocolopt) → {socket}nullable

Creates a network socket instance.

This function creates a new network socket with the specified domain and type, determined by one of the modules AF_* and SOCK_* constants respectively, and returns the resulting socket instance for use in subsequent socket operations.

The domain argument specifies the protocol family, such as AF_INET or AF_INET6, and defaults to AF_INET if not provided.

The type argument specifies the socket type, such as SOCK_STREAM or SOCK_DGRAM, and defaults to SOCK_STREAM if not provided. It may also be bitwise OR-ed with SOCK_NONBLOCK to enable non-blocking mode or SOCK_CLOEXEC to enable close-on-exec semantics.

The protocol argument may be used to indicate a particular protocol to be used with the socket, and it defaults to 0 (automatically determined protocol) if not provided.

Returns a socket descriptor representing the newly created socket.

Returns null if an error occurred during socket creation.

Parameters:
NameTypeDescription
domainnumber(optional, default: AF_INET)

The communication domain for the socket, e.g., AF_INET or AF_INET6.

typenumber(optional, default: SOCK_STREAM)

The socket type, e.g., SOCK_STREAM or SOCK_DGRAM. It may also be bitwise OR-ed with SOCK_NONBLOCK or SOCK_CLOEXEC.

protocolnumber(optional, default: 0)

The protocol to be used with the socket.

Returns: socket

A socket instance representing the newly created socket.

Example
// Create a TCP socket
const tcp_socket = create(AF_INET, SOCK_STREAM);

// Create a nonblocking IPv6 UDP socket
const udp_socket = create(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK);

error(numericopt) → {string|number}

Query error information.

Returns a string containing a description of the last occurred error when the numeric argument is absent or false.

Returns a positive (errno) or negative (EAI_* constant) error code number when the numeric argument is true.

Returns null if there is no error information.

Parameters:
NameTypeDescription
numericboolean(optional)

Whether to return a numeric error code (true) or a human readable error message (false).

Returns: string | number
Example
// Trigger socket error by attempting to bind IPv6 address with IPv4 socket
socket.create(socket.AF_INET, socket.SOCK_STREAM, 0).bind("::", 8080);

// Print error (should yield "Address family not supported by protocol")
print(socket.error(), "\n");

// Trigger resolve error
socket.addrinfo("doesnotexist.org");

// Query error code (should yield -2 for EAI_NONAME)
print(socket.error(true), "\n");  //

listen(host, serviceopt, hintsopt, backlogopt) → {socket}

Binds a listening network socket to the specified host and service.

This high-level function combines the functionality of create(), addrinfo(), bind(), and listen() to simplify setting up a listening socket with the socket module.

Parameters:
NameTypeDescription
hoststring | number[] | socket.SocketAddress

The host to bind to, can be an IP address, hostname, SocketAddress, or an array value returned by iptoarr().

servicestring | number(optional)

The service to listen on, can be a symbolic service name (such as "http") or a port number. Optional if host is specified as SocketAddress.

hintsObject(optional)

Optional preferences for the socket. It can contain the following properties:

  • family: The preferred address family (AF_INET or AF_INET6).
  • socktype: The socket type (SOCK_STREAM, SOCK_DGRAM, etc.).
  • protocol: The protocol of the created socket.
  • flags: Bitwise OR-ed AI_* flags to control the resolution behavior.

If no hints are provided, the default socket type preference is set to SOCK_STREAM.

backlognumber(optional, default: 128)

The maximum length of the queue of pending connections.

Returns: socket
Example
// Listen for incoming TCP connections on port 80
let server = socket.listen("localhost", 80);

// Listen on IPv6 address only
let server = socket.listen("machine.local", 8080, { family: socket.AF_INET6 });

// Listen on a UNIX domain socket
let server = socket.listen({ path: "/var/run/server.sock" });

nameinfo(address, flagsopt) → {Object}nullable

Resolves the given network address into hostname and service name.

The nameinfo() function provides an API for reverse DNS lookup and service name resolution. It returns an object containing the following properties:

  • hostname: The resolved hostname.
  • service: The resolved service name.

Returns an object representing the resolved hostname and service name. Return null if an error occurred during resolution.

Parameters:
NameTypeDescription
addressstring | socket.SocketAddress

The network address to resolve. It can be specified as:

  • A string representing the IP address.
  • An object representing the address with properties address and port.
flagsnumber(optional)

Optional flags that provide additional control over the resolution process, specified as bitwise OR-ed number of NI_* constants.

Returns: Object
Example
// Resolve a network address into hostname and service name
const result = network.getnameinfo('192.168.1.1:80');
print(result); // { "hostname": "example.com", "service": "http" }
See
  • Socket Types
  • AName Info Constants

poll(timeout, …sockets) → {PollSpec[]}

Polls a number of sockets for state changes.

Returns an array of [socket, flags] tuples for each socket with pending events. When a tuple is passed as socket argument, it is included as-is into the result tuple array, with the flags entry changed to a bitwise OR-ed value describing the pending events for this socket. When a plain socket instance (or another kind of handle) is passed, a new tuple array is created for this socket within the result tuple array, containing this socket as first and the bitwise OR-ed pending events as second element.

Returns null if an error occurred.

Parameters:
NameTypeDescription
timeoutnumber

Amount of milliseconds to wait for socket activity before aborting the poll call. If set to 0, the poll call will return immediately if none of the provided sockets has pending events, if set to a negative value, the poll call will wait indefinitely, in all other cases the poll call will wait at most for the given amount of milliseconds before returning.

socketssocket | PollSpec(repeatable)

An arbitrary amount of socket arguments. Each argument may be either a plain socket instance (or any other kind of handle implementing a fileno() method) or a [socket, flags] tuple specifying the socket and requested poll flags. If a plain socket (or other kind of handle) instead of a tuple is provided, the requested poll flags default to POLLIN|POLLERR|POLLHUP for this socket.

Returns: PollSpec[]
Example
let x = socket.connect("example.org", 80);
let y = socket.connect("example.com", 80);

// Pass plain socket arguments
let events = socket.poll(10, x, y);
print(events); // [ [ "<socket 0x7>", 0 ], [ "<socket 0x8>", 0 ] ]

// Passing tuples allows attaching state information and requesting
// different I/O events
let events = socket.poll(10,
	[ x, socket.POLLOUT | socket.POLLHUP, "This is example.org" ],
	[ y, socket.POLLOUT | socket.POLLHUP, "This is example.com" ]
);
print(events); // [ [ "<socket 0x7>", 4, "This is example.org" ],
               //   [ "<socket 0x8>", 4, "This is example.com" ] ]

sockaddr(address) → {socket.SocketAddress}nullable

Parses the provided address value into a socket address representation.

This function parses the given address value into a socket address representation required for a number of socket operations. The address value can be provided in various formats:

  • For IPv4 addresses, it can be a string representing the IP address, optionally followed by a port number separated by colon, e.g. 192.168.0.1:8080.
  • For IPv6 addresses, it must be an address string enclosed in square brackets if a port number is specified, otherwise the brackets are optional. The address string may also include a scope ID in the form %ifname or %number, e.g. [fe80::1%eth0]:8080 or fe80::1%15.
  • Any string value containing a slash is treated as UNIX domain socket path.
  • Alternatively, it can be provided as an array returned by iptoarr(), representing the address octets.
  • It can also be an object representing a network address, with properties for address (the IP address) and port or a single property path to denote a UNIX domain socket address.
Parameters:
NameTypeDescription
addressstring | number[] | socket.SocketAddress

The address value to parse.

Returns: socket.SocketAddress

A socket address representation of the provided address value, or null if the address could not be parsed.

Example
// Parse an IP address string with port
const address1 = sockaddr('192.168.0.1:8080');

// Parse an IPv6 address string with port and scope identifier
const address2 = sockaddr('[fe80::1%eth0]:8080');

// Parse an array representing an IP address
const address3 = sockaddr([192, 168, 0, 1]);

// Parse a network address object
const address4 = sockaddr({ address: '192.168.0.1', port: 8080 });

// Convert a path value to a UNIX domain socket address
const address5 = sockaddr('/var/run/daemon.sock');

Type Definitions

AddressInfo: Object

Represents a network address information object returned by addrinfo().

Properties
NameTypeAttributesDefaultDescription
addrsocket.SocketAddress

A socket address structure.

canonnamestringoptionalnull(optional, default: null)

The canonical hostname associated with the address.

familynumber

The address family (e.g., 2 for AF_INET, 10 for AF_INET6).

flagsnumber

Additional flags indicating properties of the address.

protocolnumber

The protocol number.

socktypenumber

The socket type (e.g., 1 for SOCK_STREAM, 2 for SOCK_DGRAM).

PollSpec: Array

Represents a poll state serving as input parameter and return value type for poll().

Properties
NameTypeDescription
0socket

The polled socket instance.

1number

Requested or returned status flags of the polled socket instance.

Address Families

Constants representing address families and socket domains.

Properties
NameTypeDescription
AF_UNSPECnumber

Unspecified address family.

AF_UNIXnumber

UNIX domain sockets.

AF_INETnumber

IPv4 Internet protocols.

AF_INET6number

IPv6 Internet protocols.

AF_PACKETnumber

Low-level packet interface.

Address Info Flags

The AI_* flags may be passed as bitwise OR-ed number in the flags property of the hints dictionary argument of addrinfo().

Properties
NameTypeDescription
AI_ADDRCONFIGnumber

Address configuration flag.

AI_ALLnumber

Return IPv4 and IPv6 socket addresses.

AI_CANONIDNnumber

Canonicalize using the IDNA standard.

AI_CANONNAMEnumber

Fill in the canonical name field.

AI_IDNnumber

Enable IDN encoding.

AI_NUMERICHOSTnumber

Prevent hostname resolution.

AI_NUMERICSERVnumber

Prevent service name resolution.

AI_PASSIVEnumber

Use passive socket.

AI_V4MAPPEDnumber

Map IPv6 addresses to IPv4-mapped format.

IP Protocol Constants

The IPPROTO_IP constant specifies the IP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IP_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IP socket level.

Properties
NameTypeDescription
IPPROTO_IPnumber

Dummy protocol for IP.

IP_ADD_MEMBERSHIPnumber

Add an IP group membership.

IP_ADD_SOURCE_MEMBERSHIPnumber

Add an IP group/source membership.

IP_BIND_ADDRESS_NO_PORTnumber

Bind to the device only.

IP_BLOCK_SOURCEnumber

Block IP group/source.

IP_DROP_MEMBERSHIPnumber

Drop an IP group membership.

IP_DROP_SOURCE_MEMBERSHIPnumber

Drop an IP group/source membership.

IP_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IP_HDRINCLnumber

Header is included with data.

IP_MSFILTERnumber

Filter IP multicast source memberships.

IP_MTUnumber

Path MTU discovery.

IP_MTU_DISCOVERnumber

Control Path MTU discovery.

IP_MULTICAST_ALLnumber

Receive all multicast packets.

IP_MULTICAST_IFnumber

Set outgoing interface for multicast packets.

IP_MULTICAST_LOOPnumber

Control multicast packet looping.

IP_MULTICAST_TTLnumber

Set time-to-live for outgoing multicast packets.

IP_NODEFRAGnumber

Don't fragment IP packets.

IP_OPTIONSnumber

Set/get IP options.

IP_PASSSECnumber

Pass security information.

IP_PKTINFOnumber

Receive packet information.

IP_RECVERRnumber

Receive all ICMP errors.

IP_RECVOPTSnumber

Receive all IP options.

IP_RECVORIGDSTADDRnumber

Receive original destination address of the socket.

IP_RECVTOSnumber

Receive IP TOS.

IP_RECVTTLnumber

Receive IP TTL.

IP_RETOPTSnumber

Set/get IP options.

IP_ROUTER_ALERTnumber

Receive ICMP msgs generated by router.

IP_TOSnumber

IP type of service and precedence.

IP_TRANSPARENTnumber

Transparent proxy support.

IP_TTLnumber

IP time-to-live.

IP_UNBLOCK_SOURCEnumber

Unblock IP group/source.

IPv6: Object

The IPPROTO_IPV6 constant specifies the IPv6 protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IPV6_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IPV6 socket level.

Properties
NameTypeDescription
IPPROTO_IPV6number

The IPv6 protocol.

IPV6_ADDRFORMnumber

Turn an AF_INET6 socket into a socket of a different address family. Only AF_INET is supported.

IPV6_ADDR_PREFERENCESnumber

Specify preferences for address selection.

IPV6_ADD_MEMBERSHIPnumber

Add an IPv6 group membership.

IPV6_AUTHHDRnumber

Set delivery of the authentication header control message for incoming datagrams.

IPV6_AUTOFLOWLABELnumber

Enable or disable automatic flow labels.

IPV6_DONTFRAGnumber

Control whether the socket allows IPv6 fragmentation.

IPV6_DROP_MEMBERSHIPnumber

Drop an IPv6 group membership.

IPV6_DSTOPTSnumber

Set delivery of the destination options control message for incoming datagrams.

IPV6_FLOWINFO_SENDnumber

Control whether flow information is sent.

IPV6_FLOWINFOnumber

Set delivery of the flow ID control message for incoming datagrams.

IPV6_FLOWLABEL_MGRnumber

Manage flow labels.

IPV6_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IPV6_HOPLIMITnumber

Set delivery of the hop limit control message for incoming datagrams.

IPV6_HOPOPTSnumber

Set delivery of the hop options control message for incoming datagrams.

IPV6_JOIN_ANYCASTnumber

Join an anycast group.

IPV6_LEAVE_ANYCASTnumber

Leave an anycast group.

IPV6_MINHOPCOUNTnumber

Set the minimum hop count.

IPV6_MTUnumber

Retrieve or set the MTU to be used for the socket.

IPV6_MTU_DISCOVERnumber

Control path-MTU discovery on the socket.

IPV6_MULTICAST_ALLnumber

Control whether the socket receives all multicast packets.

IPV6_MULTICAST_HOPSnumber

Set the multicast hop limit for the socket.

IPV6_MULTICAST_IFnumber

Set the device for outgoing multicast packets on the socket.

IPV6_MULTICAST_LOOPnumber

Control whether the socket sees multicast packets that it has sent itself.

IPV6_PKTINFOnumber

Set delivery of the IPV6_PKTINFO control message on incoming datagrams.

IPV6_RECVDSTOPTSnumber

Control receiving of the destination options control message.

IPV6_RECVERRnumber

Control receiving of asynchronous error options.

IPV6_RECVFRAGSIZEnumber

Control receiving of fragment size.

IPV6_RECVHOPLIMITnumber

Control receiving of hop limit.

IPV6_RECVHOPOPTSnumber

Control receiving of hop options.

IPV6_RECVORIGDSTADDRnumber

Control receiving of the original destination address.

IPV6_RECVPATHMTUnumber

Control receiving of path MTU.

IPV6_RECVPKTINFOnumber

Control receiving of packet information.

IPV6_RECVRTHDRnumber

Control receiving of routing header.

IPV6_RECVTCLASSnumber

Control receiving of traffic class.

IPV6_ROUTER_ALERT_ISOLATEnumber

Control isolation of router alert messages.

IPV6_ROUTER_ALERTnumber

Pass forwarded packets containing a router alert hop-by-hop option to this socket.

IPV6_RTHDRnumber

Set delivery of the routing header control message for incoming datagrams.

IPV6_RTHDRDSTOPTSnumber

Set delivery of the routing header destination options control message.

IPV6_TCLASSnumber

Set the traffic class.

IPV6_TRANSPARENTnumber

Enable transparent proxy support.

IPV6_UNICAST_HOPSnumber

Set the unicast hop limit for the socket.

IPV6_UNICAST_IFnumber

Set the interface for outgoing unicast packets.

IPV6_V6ONLYnumber

Restrict the socket to sending and receiving IPv6 packets only.

Message Flags

The MSG_* flag constants are commonly used in conjunction with the send() and recv() functions.

Properties
NameTypeDescription
MSG_CONFIRMnumber

Confirm path validity.

MSG_DONTROUTEnumber

Send without using routing tables.

MSG_DONTWAITnumber

Enables non-blocking operation.

MSG_EORnumber

End of record.

MSG_MOREnumber

Sender will send more.

MSG_NOSIGNALnumber

Do not generate SIGPIPE.

MSG_OOBnumber

Process out-of-band data.

MSG_FASTOPENnumber

Send data in TCP SYN.

MSG_CMSG_CLOEXECnumber

Sets the close-on-exec flag on the received file descriptor.

MSG_ERRQUEUEnumber

Receive errors from ICMP.

MSG_PEEKnumber

Peeks at incoming messages.

MSG_TRUNCnumber

Report if datagram truncation occurred.

MSG_WAITALLnumber

Wait for full message.

Name Info Constants

The NI_* flags may be passed as bitwise OR-ed number via the flags argument of nameinfo().

Properties
NameTypeDescription
NI_DGRAMnumber

Datagram socket type.

NI_IDNnumber

Enable IDN encoding.

NI_NAMEREQDnumber

Hostname resolution required.

NI_NOFQDNnumber

Do not force fully qualified domain name.

NI_NUMERICHOSTnumber

Return numeric form of the hostname.

NI_NUMERICSERVnumber

Return numeric form of the service name.

Packet Socket Constants

The SOL_PACKET constant specifies the packet socket level and may be passed as level argument value to getopt() and setopt().

Most PACKET_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the SOL_PACKET socket level.

The constants PACKET_MR_PROMISC, PACKET_MR_MULTICAST and PACKET_MR_ALLMULTI are used in conjunction with the PACKET_ADD_MEMBERSHIP and PACKET_DROP_MEMBERSHIP options to specify the packet socket receive mode.

The constants PACKET_HOST, PACKET_BROADCAST, PACKET_MULTICAST, PACKET_OTHERHOST and PACKET_OUTGOING may be used as packet_type value in socket address structures.

Properties
NameTypeDescription
SOL_PACKETnumber

Socket options at the packet API level.

PACKET_ADD_MEMBERSHIPnumber

Add a multicast group membership.

PACKET_DROP_MEMBERSHIPnumber

Drop a multicast group membership.

PACKET_AUXDATAnumber

Receive auxiliary data (packet info).

PACKET_FANOUTnumber

Configure packet fanout.

PACKET_LOSSnumber

Retrieve the current packet loss statistics.

PACKET_RESERVEnumber

Reserve space for packet headers.

PACKET_RX_RINGnumber

Configure a receive ring buffer.

PACKET_STATISTICSnumber

Retrieve packet statistics.

PACKET_TIMESTAMPnumber

Retrieve packet timestamps.

PACKET_TX_RINGnumber

Configure a transmit ring buffer.

PACKET_VERSIONnumber

Set the packet protocol version.

PACKET_QDISC_BYPASSnumber

Bypass queuing discipline for outgoing packets.

PACKET_MR_PROMISCnumber

Enable promiscuous mode.

PACKET_MR_MULTICASTnumber

Receive multicast packets.

PACKET_MR_ALLMULTInumber

Receive all multicast packets.

PACKET_HOSTnumber

Receive packets destined for this host.

PACKET_BROADCASTnumber

Receive broadcast packets.

PACKET_MULTICASTnumber

Receive multicast packets.

PACKET_OTHERHOSTnumber

Receive packets destined for other hosts.

PACKET_OUTGOINGnumber

Transmit packets.

Poll Event Constants

The following constants represent event types for polling operations and are set or returned as part of a PollSpec tuple by the poll() function. When passed via an argument PollSpec to poll(), they specify the I/O events to watch for on the corresponding handle. When appearing in a PollSpec returned by poll(), they specify the I/O events that occurred on a watched handle.

Properties
NameTypeDescription
POLLINnumber

Data available to read.

POLLPRInumber

Priority data available to read.

POLLOUTnumber

Writable data available.

POLLERRnumber

Error condition.

POLLHUPnumber

Hang up.

POLLNVALnumber

Invalid request.

POLLRDHUPnumber

Peer closed or shutdown writing.

Shutdown Constants

The SHUT_* constants are passed as argument to the shutdown() function to specify which direction of a full duplex connection to shut down.

Properties
NameTypeDescription
SHUT_RDnumber

Disallow further receptions.

SHUT_WRnumber

Disallow further transmissions.

SHUT_RDWRnumber

Disallow further receptions and transmissions.

Socket Option Constants

The SOL_SOCKET constant is passed as level argument to the getopt() and setopt() functions in order to set or retrieve generic socket option values.

The SO_* constants are passed as option argument in conjunction with the SOL_SOCKET level to specify the specific option to get or set on the socket.

Properties
NameTypeDescription
SOL_SOCKETnumber

Socket options at the socket API level.

SO_ACCEPTCONNnumber

Reports whether socket listening is enabled.

SO_ATTACH_BPFnumber

Attach BPF program to socket.

SO_ATTACH_FILTERnumber

Attach a socket filter.

SO_ATTACH_REUSEPORT_CBPFnumber

Attach BPF program for cgroup and skb program reuseport hook.

SO_ATTACH_REUSEPORT_EBPFnumber

Attach eBPF program for cgroup and skb program reuseport hook.

SO_BINDTODEVICEnumber

Bind socket to a specific interface.

SO_BROADCASTnumber

Allow transmission of broadcast messages.

SO_BUSY_POLLnumber

Enable busy polling.

SO_DEBUGnumber

Enable socket debugging.

SO_DETACH_BPFnumber

Detach BPF program from socket.

SO_DETACH_FILTERnumber

Detach a socket filter.

SO_DOMAINnumber

Retrieves the domain of the socket.

SO_DONTROUTEnumber

Send packets directly without routing.

SO_ERRORnumber

Retrieves and clears the error status for the socket.

SO_INCOMING_CPUnumber

Retrieves the CPU number on which the last packet was received.

SO_INCOMING_NAPI_IDnumber

Retrieves the NAPI ID of the device.

SO_KEEPALIVEnumber

Enable keep-alive packets.

SO_LINGERnumber

Set linger on close.

SO_LOCK_FILTERnumber

Set or get the socket filter lock state.

SO_MARKnumber

Set the mark for packets sent through the socket.

SO_OOBINLINEnumber

Enables out-of-band data to be received in the normal data stream.

SO_PASSCREDnumber

Enable the receiving of SCM_CREDENTIALS control messages.

SO_PASSSECnumber

Enable the receiving of security context.

SO_PEEK_OFFnumber

Returns the number of bytes in the receive buffer without removing them.

SO_PEERCREDnumber

Retrieves the credentials of the foreign peer.

SO_PEERSECnumber

Retrieves the security context of the foreign peer.

SO_PRIORITYnumber

Set the protocol-defined priority for all packets.

SO_PROTOCOLnumber

Retrieves the protocol number.

SO_RCVBUFnumber

Set the receive buffer size.

SO_RCVBUFFORCEnumber

Set the receive buffer size forcefully.

SO_RCVLOWATnumber

Set the minimum number of bytes to process for input operations.

SO_RCVTIMEOnumber

Set the timeout for receiving data.

SO_REUSEADDRnumber

Allow the socket to be bound to an address that is already in use.

SO_REUSEPORTnumber

Enable duplicate address and port bindings.

SO_RXQ_OVFLnumber

Reports if the receive queue has overflown.

SO_SNDBUFnumber

Set the send buffer size.

SO_SNDBUFFORCEnumber

Set the send buffer size forcefully.

SO_SNDLOWATnumber

Set the minimum number of bytes to process for output operations.

SO_SNDTIMEOnumber

Set the timeout for sending data.

SO_TIMESTAMPnumber

Enable receiving of timestamps.

SO_TIMESTAMPNSnumber

Enable receiving of nanosecond timestamps.

SO_TYPEnumber

Retrieves the type of the socket (e.g., SOCK_STREAM).

Socket Types

The SOCK_* type and flag constants are used by create() to specify the type of socket to open. The accept() function recognizes the SOCK_NONBLOCK and SOCK_CLOEXEC flags and applies them to accepted peer sockets.

Properties
NameTypeDescription
SOCK_STREAMnumber

Provides sequenced, reliable, two-way, connection-based byte streams.

SOCK_DGRAMnumber

Supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_RAWnumber

Provides raw network protocol access.

SOCK_PACKETnumber

Obsolete and should not be used.

SOCK_NONBLOCKnumber

Enables non-blocking operation.

SOCK_CLOEXECnumber

Sets the close-on-exec flag on the new file descriptor.

TCP Protocol Constants

The IPPROTO_TCP constant specifies the TCP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The TCP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_TCP socket level.

Properties
NameTypeDescription
IPPROTO_TCPnumber

TCP protocol.

TCP_CONGESTIONnumber

Set the congestion control algorithm.

TCP_CORKnumber

Delay packet transmission until full-sized packets are available.

TCP_DEFER_ACCEPTnumber

Delay accepting incoming connections until data arrives.

TCP_FASTOPENnumber

Enable TCP Fast Open.

TCP_FASTOPEN_CONNECTnumber

Perform TFO connect.

TCP_INFOnumber

Retrieve TCP statistics.

TCP_KEEPCNTnumber

Number of keepalive probes.

TCP_KEEPIDLEnumber

Time before keepalive probes begin.

TCP_KEEPINTVLnumber

Interval between keepalive probes.

TCP_LINGER2number

Lifetime of orphaned FIN_WAIT2 state sockets.

TCP_MAXSEGnumber

Maximum segment size.

TCP_NODELAYnumber

Disable Nagle's algorithm.

TCP_QUICKACKnumber

Enable quick ACKs.

TCP_SYNCNTnumber

Number of SYN retransmits.

TCP_USER_TIMEOUTnumber

Set the user timeout.

TCP_WINDOW_CLAMPnumber

Set the maximum window.

UDP Protocol Constants

The IPPROTO_UDP constant specifies the UDP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The UDP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_UDP socket level.

Properties
NameTypeDescription
IPPROTO_UDPnumber

UDP protocol.

UDP_CORKnumber

Cork data until flush.