socket. socket

Represents a socket handle.

Example
const sock = create(…);

sock.getopt(…);
sock.setopt(…);

sock.connect(…);
sock.listen(…);
sock.accept(…);
sock.bind(…);

sock.send(…);
sock.recv(…);

sock.shutdown(…);

sock.fileno();
sock.peername();
sock.sockname();

sock.close();

sock.error();

Methods

accept(addressopt, flagsopt) → {socket}nullable

Accept a connection on a socket.

This function accepts a connection on the socket. It extracts the first connection request on the queue of pending connections, creates a new connected socket, and returns a new socket handle referring to that socket. The newly created socket is not in listening state and has no backlog.

When a optional address dictionary is provided, it is populated with the remote address details of the peer socket.

The optional flags parameter is a bitwise-or-ed number of flags to modify the behavior of accepted peer socket. Possible values are:

  • SOCK_CLOEXEC: Enable close-on-exec semantics for the new socket.
  • SOCK_NONBLOCK: Enable nonblocking mode for the new socket.

Returns a socket handle representing the newly created peer socket of the accepted connection.

Returns null if an error occurred.

Parameters:
NameTypeDescription
addressobject(optional)

An optional dictionary to receive the address details of the peer socket. See SocketAddress for details.

flagsnumber(optional)

Optional flags to modify the behavior of the peer socket.

Returns: socket
Example
const sock = socket.create(…);
sock.bind(…);
sock.listen();

const peerAddress = {};
const newSocket = sock.accept(peerAddress, socket.SOCK_CLOEXEC);
if (newSocket)
    print(`Accepted connection from: ${peerAddress}\n`);
else
    print(`Failed to accept connection: ${sock.error()}\n`);

bind(address) → {boolean}nullable

Binds a socket to a specific address.

This function binds the socket to the specified address.

Returns true if the socket is successfully bound.

Returns null on error, e.g. when the address is in use.

Parameters:
NameTypeDescription
addressstring | SocketAddress

The IP address to bind the socket to.

Returns: boolean
Example
const sock = socket.create(…);
const success = sock.bind("192.168.0.1:80");

if (success)
    print(`Socket bound successfully!\n`);
else
    print(`Failed to bind socket: ${sock.error()}.\n`);

close() → {boolean}nullable

Closes the socket.

This function closes the socket, releasing its resources and terminating its associated connections.

Returns true if the socket was successfully closed. Returns null on error.

Returns: boolean
Example
const sock = socket.create(…);
sock.connect(…);
// Perform operations with the socket…
sock.close();

connect(address, port) → {boolean}nullable

Connects the socket to a remote address.

Attempts to establish a connection to the specified remote address.

Returns true if the connection is successfully established. Returns null if an error occurred during the connection attempt.

Parameters:
NameTypeDescription
addressstring | SocketAddress

The address of the remote endpoint to connect to.

portnumber

The port number of the remote endpoint to connect to.

Returns: boolean

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");  //

fileno() → {number}

Returns the UNIX file descriptor number associated with the socket.

Returns the file descriptor number.

Returns -1 if an error occurred.

Returns: number

getopt(level, option) → {*}nullable

Gets options from the socket.

Retrieves the value of the specified option from the socket.

Returns the value of the requested option.

Returns null if an error occurred or if the option is not supported.

Parameters:
NameTypeDescription
levelnumber

The protocol level at which the option resides. This can be a level such as SOL_SOCKET for the socket API level or a specific protocol level defined by the system.

optionnumber

The socket option to retrieve. This can be an integer representing the option, such as SO_REUSEADDR, or a constant defined by the system.

Returns: *

The value of the requested option. The type of the returned value depends on the specific option being retrieved. It can be an integer, a boolean, a string, or a dictionary representing a complex data structure.

listen(backlogopt) → {boolean}nullable

Listen for connections on a socket.

This function marks the socket as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept().

The backlog parameter specifies the maximum length to which the queue of pending connections may grow. If a connection request arrives when the queue is full, the client connection might get refused.

If backlog is not provided, it defaults to 128.

Returns true if the socket is successfully marked as passive. Returns null if an error occurred, e.g. when the requested port is in use.

Parameters:
NameTypeDescription
backlognumber(optional, default: 128)

The maximum length of the queue of pending connections.

Returns: boolean
Example
const sock = socket.create(…);
sock.bind(…);

const success = sock.listen(10);
if (success)
    print(`Socket is listening for incoming connections!\n`);
else
    print(`Failed to listen on socket: ${sock.error()}\n`);

peercred() → {PeerCredentials}nullable

Retrieves the peer credentials.

This function retrieves the remote uid, gid and pid of a connected UNIX domain socket.

Returns the remote credentials if the operation is successful. Returns null on error.

Example
const sock = socket.create(socket.AF_UNIX, …);
sock.connect(…);

const peerCredentials = sock.peercred();
if (peerCredentials)
    print(`Peer credentials: ${peerCredentials}\n`);
else
    print(`Failed to retrieve peer credentials: ${sock.error()}\n`);

peername() → {SocketAddress}nullable

Retrieves the remote address.

This function retrieves the remote address of a connected socket.

Returns the remote address if the operation is successful. Returns null on error.

Returns: SocketAddress
Example
const sock = socket.create(…);
sock.connect(…);

const peerAddress = sock.peername();
if (peerAddress)
    print(`Connected to ${peerAddress}\n`);
else
    print(`Failed to retrieve peer address: ${sock.error()}\n`);

recv(lengthopt, flagsopt, addressopt) → {string}nullable

Receives data from the socket.

Receives data from the socket handle, optionally specifying the maximum length of data to receive, flags to modify the receive behavior, and an optional address dictionary where the function will place the address from which the data was received (for unconnected sockets).

Returns a string containing the received data. Returns an empty string if the remote side closed the socket. Returns null if an error occurred during the receive operation.

Parameters:
NameTypeDescription
lengthnumber(optional, default: 4096)

The maximum number of bytes to receive.

flagsnumber(optional)

Optional flags that modify the behavior of the receive operation.

addressObject(optional)

An object where the function will store the address from which the data was received. If provided, it will be filled with the details obtained from the sockaddr argument of the underlying recvfrom() syscall. See the type definition of SocketAddress for details on the format.

Returns: string

recvmsg(sizesopt, ancillarySizeopt, flagsopt) → {ReceivedMessage}nullable

Receives a message from the socket.

Receives a message from the socket handle, allowing for more complex data reception compared to recv(). This includes the ability to receive ancillary data (such as file descriptors, credentials, etc.), multiple message segments, and optional flags to modify the receive behavior.

Returns an object containing the received message data, ancillary data, and the sender's address.

Returns null if an error occurred during the receive operation.

Parameters:
NameTypeDescription
sizesnumber[] | number(optional)

Specifies the sizes of the buffers used for receiving the message. If an array of numbers is provided, each number determines the size of an individual buffer segment, creating multiple struct iovec for reception. If a single number is provided, a single buffer of that size is used.

ancillarySizenumber(optional)

The size allocated for the ancillary data buffer. If not provided, ancillary data is not processed.

flagsnumber(optional)

Optional flags to modify the behavior of the receive operation. This should be a bitwise OR-ed combination of flag values.

Returns: ReceivedMessage

An object containing the received message data, ancillary data, and the sender's address.

Example
// Receive file descriptors over domain socket
const sk = socket.listen({ family: socket.AF_UNIX, path: "/tmp/socket" });
sk.setopt(socket.SOL_SOCKET, socket.SO_PASSCRED, true);

const msg = sk.recvmsg(1024, 1024); *
for (let cmsg in msg.ancillary)
  if (cmsg.level == socket.SOL_SOCKET && cmsg.type == socket.SCM_RIGHTS)
    print(`Got some descriptors: ${cmsg.data}!\n`);

// Receive message in segments of 10, 128 and 512 bytes
const msg = sk.recvmsg([ 10, 128, 512 ]);
print(`Message parts: ${msg.data[0]}, ${msg.data[1]}, ${msg.data[2]}\n`);

// Peek buffer
const msg = sk.recvmsg(0, 0, socket.MSG_PEEK|socket.MSG_TRUNC);
print(`Received ${length(msg.data)} bytes, ${msg.length} bytes available\n`);

send(data, flagsopt, addressopt) → {number}nullable

Sends data through the socket.

Sends the provided data through the socket handle to the specified remote address, if provided.

Returns the number of bytes sent. Returns null if an error occurred during the send operation.

Parameters:
NameTypeDescription
data*

The data to be sent through the socket. String data is sent as-is, any other type is implicitly converted to a string first before being sent on the socket.

flagsnumber(optional)

Optional flags that modify the behavior of the send operation.

addressSocketAddress | number[] | string(optional)

The address of the remote endpoint to send the data to. It can be either an IP address string, an array returned by iptoarr(), or an object representing a network address. If not provided, the data is sent to the remote endpoint the socket is connected to.

Returns: number
Example
// Send to connected socket
let tcp_sock = socket.create(socket.AF_INET, socket.SOCK_STREAM);
tcp_sock.connect("192.168.1.1", 80);
tcp_sock.send("GET / HTTP/1.0\r\n\r\n");

// Send a datagram on unconnected socket
let udp_sock = socket.create(socket.AF_INET, socket.SOCK_DGRAM);
udp_sock.send("Hello there!", 0, "255.255.255.255:9000");
udp_sock.send("Hello there!", 0, {
  family: socket.AF_INET,      // optional
  address: "255.255.255.255",
  port: 9000
});

sendmsg(dataopt, ancillaryDataopt, addressopt, flagsopt) → {number}nullable

Sends a message through the socket.

Sends a message through the socket handle, supporting complex message structures including multiple data buffers and ancillary data. This function allows for precise control over the message content and delivery behavior.

Returns the number of sent bytes.

Returns null if an error occurred.

Parameters:
NameTypeDescription
data*(optional)

The data to be sent. If a string is provided, it is sent as is. If an array is specified, each item is sent as a separate struct iovec. Non-string values are implicitly converted to a string and sent. If omitted, only ancillary data and address are considered.

ancillaryDataControlMessage[] | string(optional)

Optional ancillary data to be sent. If an array is provided, each element is converted to a control message. If a string is provided, it is sent as-is without further interpretation. Refer to recvmsg() and ControlMessage for details.

addressSocketAddress(optional)

The destination address for the message. If provided, it sets or overrides the packet destination address.

flagsnumber(optional)

Optional flags to modify the behavior of the send operation. This should be a bitwise OR-ed combination of MSG_* flag values.

Returns: number

Returns the number of bytes sent on success, or null if an error occurred.

Example
// Send file descriptors over domain socket
const f1 = fs.open("example.txt", "w");
const f2 = fs.popen("date +%s", "r");
const sk = socket.connect({ family: socket.AF_UNIX, path: "/tmp/socket" });
sk.sendmsg("Hi there, here's some descriptors!", [
	{ level: socket.SOL_SOCKET, type: socket.SCM_RIGHTS, data: [ f1, f2 ] }
]);

// Send multiple values in one datagram
sk.sendmsg([ "This", "is", "one", "message" ]);

setopt(level, option, value) → {boolean}nullable

Sets options on the socket.

Sets the specified option on the socket to the given value.

Returns true if the option was successfully set.

Returns null if an error occurred.

Parameters:
NameTypeDescription
levelnumber

The protocol level at which the option resides. This can be a level such as SOL_SOCKET for the socket API level or a specific protocol level defined by the system.

optionnumber

The socket option to set. This can be an integer representing the option, such as SO_REUSEADDR, or a constant defined by the system.

value*

The value to set the option to. The type of this argument depends on the specific option being set. It can be an integer, a boolean, a string, or a dictionary representing the value to set. If a dictionary is provided, it is internally translated to the corresponding C struct type required by the option.

Returns: boolean

shutdown(how) → {boolean}nullable

Shutdown part of a full-duplex connection.

This function shuts down part of the full-duplex connection associated with the socket handle. The how parameter specifies which half of the connection to shut down. It can take one of the following constant values:

  • SHUT_RD: Disables further receive operations.
  • SHUT_WR: Disables further send operations.
  • SHUT_RDWR: Disables further send and receive operations.

Returns true if the shutdown operation is successful. Returns null if an error occurred.

Parameters:
NameTypeDescription
hownumber

Specifies which half of the connection to shut down. It can be one of the following constant values: SHUT_RD, SHUT_WR, or SHUT_RDWR.

Returns: boolean
Example
const sock = socket.create(…);
sock.connect(…);
// Perform data exchange…

const success = sock.shutdown(socket.SHUT_WR);
if (success)
    print(`Send operations on socket shut down successfully.\n`);
else
    print(`Failed to shut down send operations: ${sock.error()}\n`);

sockname() → {SocketAddress}nullable

Retrieves the local address.

This function retrieves the local address of a bound or connected socket.

Returns the local address if the operation is successful. Returns null on error.

Returns: SocketAddress
Example
const sock = socket.create(…);
sock.connect(…);

const myAddress = sock.sockname();
if (myAddress)
    print(`My source IP address is ${myAddress}\n`);
else
    print(`Failed to retrieve peer address: ${sock.error()}\n`);

Type Definitions

ControlMessage: Object

Represents a single control (ancillary data) message returned in the ancillary array by recvmsg().

Properties
NameTypeDescription
levelnumber

The message socket level (cmsg_level), e.g. SOL_SOCKET.

typenumber

The protocol specific message type (cmsg_type), e.g. SCM_RIGHTS.

data*

The payload of the control message. If the control message type is known by the socket module, it is represented as a mixed value (array, object, number, etc.) with structure specific to the control message type. If the control message cannot be decoded, data is set to a string value containing the raw payload.

PeerCredentials: Object

Represents a credentials information object returned by peercred().

Properties
NameTypeDescription
uidnumber

The effective user ID the remote socket endpoint.

gidnumber

The effective group ID the remote socket endpoint.

pidnumber

The ID of the process the remote socket endpoint belongs to.

ReceivedMessage: Object

Represents a message object returned by recvmsg().

Properties
NameTypeAttributesDescription
flagsnumber

Integer value containing bitwise OR-ed MSG_* result flags returned by the underlying receive call.

lengthnumber

Integer value containing the number of bytes returned by the recvmsg() syscall, which might be larger than the received data in case MSG_TRUNC was passed.

addressSocketAddress

The address from which the message was received.

datastring[] | string

An array of strings, each representing the received message data. Each string corresponds to one buffer size specified in the sizes argument. If a single receive size was passed instead of an array of sizes, data will hold a string containing the received data.

ancillaryControlMessage[]optional(optional)

An array of received control messages. Only included if a non-zero positive ancillarySize was passed to recvmsg().

SocketAddress: Object

Properties
NameTypeAttributesDefaultDescription
familynumber

Address family, one of AF_INET, AF_INET6, AF_UNIX or AF_PACKET.

addressstring

IPv4/IPv6 address string (AF_INET or AF_INET6 only) or hardware address in hexadecimal notation (AF_PACKET only).

portnumberoptional(optional)

Port number (AF_INET or AF_INET6 only).

flowinfonumberoptional(optional)

IPv6 flow information (AF_INET6 only).

interfacestring | numberoptional(optional)

Link local address scope (for IPv6 sockets) or bound network interface (for packet sockets), either a network device name string or a nonzero positive integer representing a network interface index (AF_INET6 and AF_PACKET only).

pathstring

Domain socket filesystem path (AF_UNIX only).

protocolnumberoptional0(optional, default: 0)

Physical layer protocol (AF_PACKET only).

hardware_typenumberoptional0(optional, default: 0)

ARP hardware type (AF_PACKET only).

packet_typenumberoptionalPACKET_HOST(optional, default: PACKET_HOST)

Packet type (AF_PACKET only).