Net#

Stability: 2 - Stable

Source Code: lib/net.js

The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()).

It can be accessed using:

import net from 'node:net';const net = require('node:net');

IPC support#

The node:net module supports IPC with named pipes on Windows, and Unix domain sockets on other operating systems.

Identifying paths for IPC connections#

net.connect(), net.createConnection(), server.listen(), and socket.connect() take a path parameter to identify IPC endpoints.

On Unix, the local domain is also known as the Unix domain. The path is a file system pathname. It will throw an error when the length of pathname is greater than the length of sizeof(sockaddr_un.sun_path). Typical values are 107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, it will unlink the Unix domain socket as well. For example, net.createServer() may create a Unix domain socket and server.close() will unlink it. But if a user creates the Unix domain socket outside of these abstractions, the user will need to remove it. The same applies when a Node.js API creates a Unix domain socket but the program then crashes. In short, a Unix domain socket will be visible in the file system and will persist until unlinked. On Linux, You can use Unix abstract socket by adding \0 to the beginning of the path, such as \0abstract. The path to the Unix abstract socket is not visible in the file system and it will disappear automatically when all open references to the socket are closed.

On Windows, the local domain is implemented using a named pipe. The path must refer to an entry in \\?\pipe\ or \\.\pipe\. Any characters are permitted, but the latter may do some processing of pipe names, such as resolving .. sequences. Despite how it might look, the pipe namespace is flat. Pipes will not persist. They are removed when the last reference to them is closed. Unlike Unix domain sockets, Windows will close and remove the pipe when the owning process exits.

JavaScript string escaping requires paths to be specified with extra backslash escaping such as:

net.createServer().listen(
  path.join('\\\\?\\pipe', process.cwd(), 'myctl')); 

Class: net.BlockList#

The BlockList object can be used with some network APIs to specify rules for disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets.

blockList.addAddress(address[, type])#

Adds a rule to block the given IP address.

blockList.addRange(start, end[, type])#

Adds a rule to block a range of IP addresses from start (inclusive) to end (inclusive).

blockList.addSubnet(net, prefix[, type])#

  • net <string> | <net.SocketAddress> The network IPv4 or IPv6 address.
  • prefix <number> The number of CIDR prefix bits. For IPv4, this must be a value between 0 and 32. For IPv6, this must be between 0 and 128.
  • type <string> Either 'ipv4' or 'ipv6'. Default: 'ipv4'.

Adds a rule to block a range of IP addresses specified as a subnet mask.

blockList.check(address[, type])#

Returns true if the given IP address matches any of the rules added to the BlockList.

const blockList = new net.BlockList();
blockList.addAddress('123.123.123.123');
blockList.addRange('10.0.0.1', '10.0.0.10');
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');

console.log(blockList.check('123.123.123.123'));  // Prints: true
console.log(blockList.check('10.0.0.3'));  // Prints: true
console.log(blockList.check('222.111.111.222'));  // Prints: false

// IPv6 notation for IPv4 addresses works:
console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true 

blockList.rules#

The list of rules added to the blocklist.

BlockList.isBlockList(value)#

  • value <any> Any JS value
  • Returns true if the value is a net.BlockList.

blockList.fromJSON(value)#

Stability: 1 - Experimental

const blockList = new net.BlockList();
const data = [
  'Subnet: IPv4 192.168.1.0/24',
  'Address: IPv4 10.0.0.5',
  'Range: IPv4 192.168.2.1-192.168.2.10',
  'Range: IPv4 10.0.0.1-10.0.0.10',
];
blockList.fromJSON(data);
blockList.fromJSON(JSON.stringify(data)); 
  • value Blocklist.rules

blockList.toJSON()#

Stability: 1 - Experimental

  • Returns Blocklist.rules

Class: net.SocketAddress#

new net.SocketAddress([options])#

  • options <Object>
    • address <string> The network address as either an IPv4 or IPv6 string. Default: '127.0.0.1' if family is 'ipv4'; '::' if family is 'ipv6'.
    • family <string> One of either 'ipv4' or 'ipv6'. Default: 'ipv4'.
    • flowlabel <number> An IPv6 flow-label used only if family is 'ipv6'.
    • port <number> An IP port.

socketaddress.address#

socketaddress.family#

  • Type: <string> Either 'ipv4' or 'ipv6'.

socketaddress.flowlabel#

socketaddress.port#

SocketAddress.parse(input)#

  • input <string> An input string containing an IP address and optional port, e.g. 123.1.2.3:1234 or [1::1]:1234.
  • Returns: <net.SocketAddress> Returns a SocketAddress if parsing was successful. Otherwise returns undefined.

Class: net.Server#

This class is used to create a TCP or IPC server.

new net.Server([options][, connectionListener])#

net.Server is an EventEmitter with the following events:

Event: 'close'#

Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.

Event: 'connection'#

Emitted when a new connection is made. socket is an instance of net.Socket.

Event: 'error'#

Emitted when an error occurs. Unlike net.Socket, the 'close' event will not be emitted directly following this event unless server.close() is manually called. See the example in discussion of server.listen().

Event: 'listening'#

Emitted when the server has been bound after calling server.listen().

Event: 'drop'#

When the number of connections reaches the threshold of server.maxConnections, the server will drop new connections and emit 'drop' event instead. If it is a TCP server, the argument is as follows, otherwise the argument is undefined.

  • data <Object> The argument passed to event listener.

server.address()#

Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

For a server listening on a pipe or Unix domain socket, the name is returned as a string.

const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  // Handle errors here.
  throw err;
});

// Grab an arbitrary unused port.
server.listen(() => {
  console.log('opened server on', server.address());
}); 

server.address() returns null before the 'listening' event has been emitted or after calling server.close().

server.close([callback])#

Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed.

server[Symbol.asyncDispose]()#

Calls server.close() and returns a promise that fulfills when the server has closed.

server.getConnections(callback)#

Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

Callback should take two arguments err and count.

server.listen()#

Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

Possible signatures:

This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callback will be added as a listener for the 'listening' event.

All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

All net.Socket are set to SO_REUSEADDR (see socket(7) for details).

The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requested port/path/handle. One way to handle this would be to retry after a certain amount of time:

server.on('error', (e) => {
  if (e.code === 'EADDRINUSE') {
    console.error('Address in use, retrying...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
}); 
server.listen(handle[, backlog][, callback])#

Start a server listening for connections on a given handle that has already been bound to a port, a Unix domain socket, or a Windows named pipe.

The handle object can be either a server, a socket (anything with an underlying _handle member), or an object with an fd member that is a valid file descriptor.

Listening on a file descriptor is not supported on Windows.

server.listen(options[, callback])#
  • options <Object> Required. Supports the following properties:
    • backlog <number> Common parameter of server.listen() functions.
    • exclusive <boolean> Default: false
    • host <string>
    • ipv6Only <boolean> For TCP servers, setting ipv6Only to true will disable dual-stack support, i.e., binding to host :: won't make 0.0.0.0 be bound. Default: false.
    • reusePort <boolean> For TCP servers, setting reusePort to true allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. Default: false.
    • path <string> Will be ignored if port is specified. See Identifying paths for IPC connections.
    • port <number>
    • readableAll <boolean> For IPC servers makes the pipe readable for all users. Default: false.
    • signal <AbortSignal> An AbortSignal that may be used to close a listening server.
    • writableAll <boolean> For IPC servers makes the pipe writable for all users. Default: false.
  • callback <Function> functions.
  • Returns: <net.Server>

If port is specified, it behaves the same as server.listen([port[, host[, backlog]]][, callback]). Otherwise, if path is specified, it behaves the same as server.listen(path[, backlog][, callback]). If none of them is specified, an error will be thrown.

If exclusive is false (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When exclusive is true, the handle is not shared, and attempted port sharing results in an error. An example which listens on an exclusive port is shown below.

server.listen({
  host: 'localhost',
  port: 80,
  exclusive: true,
}); 

When exclusive is true and the underlying handle is shared, it is possible that several workers query a handle with different backlogs. In this case, the first backlog passed to the master process will be used.

Starting an IPC server as root may cause the server path to be inaccessible for unprivileged users. Using readableAll and writableAll will make the server accessible for all users.

If the signal option is enabled, calling .abort() on the corresponding AbortController is similar to calling .close() on the server:

const controller = new AbortController();
server.listen({
  host: 'localhost',
  port: 80,
  signal: controller.signal,
});
// Later, when you want to close the server.
controller.abort(); 
server.listen(path[, backlog][, callback])#

Start an IPC server listening for connections on the given path.

server.listen([port[, host[, backlog]]][, callback])#

Start a TCP server listening for connections on the given port and host.

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the