Represents a socket handle.
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();
- Source
- See
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.
Name | Type | Description |
---|---|---|
address | object | (optional) An optional dictionary to receive the address details of the peer socket. See SocketAddress for details. |
flags | number | (optional) Optional flags to modify the behavior of the peer socket. |
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`);
- Source
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.
Name | Type | Description |
---|---|---|
address | string | | The IP address to bind the socket to. |
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`);
- Source
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.
const sock = socket.create(…);
sock.connect(…);
// Perform operations with the socket…
sock.close();
- Source
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.
Name | Type | Description |
---|---|---|
address | string | | The address of the remote endpoint to connect to. |
port | number | The port number of the remote endpoint to connect to. |
- Source
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.
Name | Type | Description |
---|---|---|
numeric | boolean | (optional) Whether to return a numeric error code ( |
// 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"); //
- Source
fileno() → {number}
Returns the UNIX file descriptor number associated with the socket.
Returns the file descriptor number.
Returns -1
if an error occurred.
- Source
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.
Name | Type | Description |
---|---|---|
level | number | The protocol level at which the option resides. This can be a level such as |
option | number | The socket option to retrieve. This can be an integer representing the option, such as |
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.
- Source
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.
Name | Type | Description |
---|---|---|
backlog | number | (optional, default: 128 )The maximum length of the queue of pending connections. |
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`);
- Source
- See
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.
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`);
- Source
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.
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`);
- Source
- See
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.
Name | Type | Description |
---|---|---|
length | number | (optional, default: 4096 )The maximum number of bytes to receive. |
flags | number | (optional) Optional flags that modify the behavior of the receive operation. |
address | Object | (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 |
- Source
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.
Name | Type | Description |
---|---|---|
sizes | 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 |
ancillarySize | number | (optional) The size allocated for the ancillary data buffer. If not provided, ancillary data is not processed. |
flags | number | (optional) Optional flags to modify the behavior of the receive operation. This should be a bitwise OR-ed combination of flag values. |
An object containing the received message data, ancillary data, and the sender's address.
// 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`);
- Source
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.
Name | Type | Description |
---|---|---|
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. |
flags | number | (optional) Optional flags that modify the behavior of the send operation. |
address | SocketAddress | | (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. |
// 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
});
- Source
- See
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.
Name | Type | Description |
---|---|---|
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 |
ancillaryData | ControlMessage[] | | (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 |
address | SocketAddress | (optional) The destination address for the message. If provided, it sets or overrides the packet destination address. |
flags | number | (optional) Optional flags to modify the behavior of the send operation. This should be a bitwise OR-ed combination of |
Returns the number of bytes sent on success, or null
if an error occurred.
// 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" ]);
- Source
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.
Name | Type | Description |
---|---|---|
level | number | The protocol level at which the option resides. This can be a level such as |
option | number | The socket option to set. This can be an integer representing the option, such as |
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. |
- Source
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.
Name | Type | Description |
---|---|---|
how | number | Specifies which half of the connection to shut down. It can be one of the following constant values: |
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`);
- Source
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.
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`);
- Source
- See
Type Definitions
ControlMessage: Object
Represents a single control (ancillary data) message returned in the ancillary array by recvmsg()
.
Name | Type | Description |
---|---|---|
level | number | The message socket level ( |
type | number | The protocol specific message type ( |
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. |
- Source
PeerCredentials: Object
Represents a credentials information object returned by peercred()
.
Name | Type | Description |
---|---|---|
uid | number | The effective user ID the remote socket endpoint. |
gid | number | The effective group ID the remote socket endpoint. |
pid | number | The ID of the process the remote socket endpoint belongs to. |
- Source
ReceivedMessage: Object
Represents a message object returned by recvmsg()
.
Name | Type | Attributes | Description |
---|---|---|---|
flags | number | Integer value containing bitwise OR-ed | |
length | number | Integer value containing the number of bytes returned by the | |
address | SocketAddress | The address from which the message was received. | |
data | 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. | |
ancillary | ControlMessage[] | optional | (optional) An array of received control messages. Only included if a non-zero positive ancillarySize was passed to |
- Source
SocketAddress: Object
PropertiesName | Type | Attributes | Default | Description |
---|---|---|---|---|
family | number | Address family, one of AF_INET, AF_INET6, AF_UNIX or AF_PACKET. | ||
address | string | IPv4/IPv6 address string (AF_INET or AF_INET6 only) or hardware address in hexadecimal notation (AF_PACKET only). | ||
port | number | optional | (optional) Port number (AF_INET or AF_INET6 only). | |
flowinfo | number | optional | (optional) IPv6 flow information (AF_INET6 only). | |
interface | string | | optional | (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). | |
path | string | Domain socket filesystem path (AF_UNIX only). | ||
protocol | number | optional | 0 | (optional, default: 0 )Physical layer protocol (AF_PACKET only). |
hardware_type | number | optional | 0 | (optional, default: 0 )ARP hardware type (AF_PACKET only). |
packet_type | number | optional | PACKET_HOST | (optional, default: PACKET_HOST )Packet type (AF_PACKET only). |
- Source