\nStability: 2 - Stable\n
Stability: 2 - Stable
Source Code: lib/net.js
The node:net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).
node:net
net.createServer()
net.createConnection()
It can be accessed using:
const net = require('node:net');\n
The node:net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.
net.connect(), net.createConnection(), server.listen(), and\nsocket.connect() take a path parameter to identify IPC endpoints.
net.connect()
server.listen()
socket.connect()
path
On Unix, the local domain is also known as the Unix domain. The path is a\nfilesystem pathname. It gets truncated to an OS-dependent length of\nsizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\nnet.createServer() may create a Unix domain socket and\nserver.close() will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the filesystem and\nwill persist until unlinked.
sizeof(sockaddr_un.sun_path) - 1
server.close()
On Windows, the local domain is implemented using a named pipe. The path must\nrefer to an entry in \\\\?\\pipe\\ or \\\\.\\pipe\\. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving ..\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\nnot persist. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.
\\\\?\\pipe\\
\\\\.\\pipe\\
..
JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:
net.createServer().listen(\n path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n
The BlockList object can be used with some network APIs to specify rules for\ndisabling inbound or outbound access to specific IP addresses, IP ranges, or\nIP subnets.
BlockList
Adds a rule to block the given IP address.
Adds a rule to block a range of IP addresses from start (inclusive) to\nend (inclusive).
start
end
Adds a rule to block a range of IP addresses specified as a subnet mask.
Returns true if the given IP address matches any of the rules added to the\nBlockList.
true
const blockList = new net.BlockList();\nblockList.addAddress('123.123.123.123');\nblockList.addRange('10.0.0.1', '10.0.0.10');\nblockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');\n\nconsole.log(blockList.check('123.123.123.123')); // Prints: true\nconsole.log(blockList.check('10.0.0.3')); // Prints: true\nconsole.log(blockList.check('222.111.111.222')); // Prints: false\n\n// IPv6 notation for IPv4 addresses works:\nconsole.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true\nconsole.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true\n
The list of rules added to the blocklist.
This class is used to create a TCP or IPC server.
Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.
Emitted when a new connection is made. socket is an instance of\nnet.Socket.
socket
net.Socket
Emitted when an error occurs. Unlike net.Socket, the 'close'\nevent will not be emitted directly following this event unless\nserver.close() is manually called. See the example in discussion of\nserver.listen().
'close'
Emitted when the server has been bound after calling server.listen().
When the number of connections reaches the threshold of server.maxConnections,\nthe server will drop new connections and emit 'drop' event instead. If it is a\nTCP server, the argument is as follows, otherwise the argument is undefined.
server.maxConnections
'drop'
undefined
data
localAddress
localPort
localFamily
remoteAddress
remotePort
remoteFamily
'IPv4'
'IPv6'
Returns the bound address, the address family name, and port of the server\nas reported by the operating system if listening on an IP socket\n(useful to find which port was assigned when getting an OS-assigned address):\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.
address
family
port
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.
const server = net.createServer((socket) => {\n socket.end('goodbye\\n');\n}).on('error', (err) => {\n // Handle errors here.\n throw err;\n});\n\n// Grab an arbitrary unused port.\nserver.listen(() => {\n console.log('opened server on', server.address());\n});\n
server.address() returns null before the 'listening' event has been\nemitted or after calling server.close().
server.address()
null
'listening'
Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally closed\nwhen all connections are ended and the server emits a 'close' event.\nThe optional callback will be called once the 'close' event occurs. Unlike\nthat event, it will be called with an Error as its only argument if the server\nwas not open when it was closed.
callback
Error
Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.
Callback should take two arguments err and count.
err
count
Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.
net.Server
Possible signatures:
server.listen(handle[, backlog][, callback])
server.listen(options[, callback])
server.listen(path[, backlog][, callback])
server.listen([port[, host[, backlog]]][, callback])
This function is asynchronous. When the server starts listening, the\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.
All listen() methods can take a backlog parameter to specify the maximum\nlength of the queue of pending connections. The actual length will be determined\nby the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn\non Linux. The default value of this parameter is 511 (not 512).
listen()
backlog
tcp_max_syn_backlog
somaxconn
All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).
SO_REUSEADDR
socket(7)
The server.listen() method can be called again if and only if there was an\nerror during the first server.listen() call or server.close() has been\ncalled. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.
ERR_SERVER_ALREADY_LISTEN
One of the most common errors raised when listening is EADDRINUSE.\nThis happens when another server is already listening on the requested\nport/path/handle. One way to handle this would be to retry\nafter a certain amount of time:
EADDRINUSE
handle
server.on('error', (e) => {\n if (e.code === 'EADDRINUSE') {\n console.log('Address in use, retrying...');\n setTimeout(() => {\n server.close();\n server.listen(PORT, HOST);\n }, 1000);\n }\n});\n
Start a server listening for connections on a given handle that has\nalready 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\nunderlying _handle member), or an object with an fd member that is a\nvalid file descriptor.
_handle
fd
Listening on a file descriptor is not supported on Windows.
If port is specified, it behaves the same as\nserver.listen([port[, host[, backlog]]][, callback]).\nOtherwise, if path is specified, it behaves the same as\nserver.listen(path[, backlog][, callback]).\nIf none of them is specified, an error will be thrown.
If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.
exclusive
false
server.listen({\n host: 'localhost',\n port: 80,\n exclusive: true\n});\n
When exclusive is true and the underlying handle is shared, it is\npossible that several workers query a handle with different backlogs.\nIn 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\nunprivileged users. Using readableAll and writableAll will make the server\naccessible for all users.
readableAll
writableAll
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the server:
signal
.abort()
AbortController
.close()
const controller = new AbortController();\nserver.listen({\n host: 'localhost',\n port: 80,\n signal: controller.signal\n});\n// Later, when you want to close the server.\ncontroller.abort();\n
Start an IPC server listening for connections on the given path.
Start a TCP server listening for connections on the given port and host.
host
If port is omitted or is 0, the operating system will assign an arbitrary\nunused port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.
server.address().port
If host is omitted, the server will accept connections on the\nunspecified IPv6 address (::) when IPv6 is available, or the\nunspecified IPv4 address (0.0.0.0) otherwise.
::
0.0.0.0
In most operating systems, listening to the unspecified IPv6 address (::)\nmay cause the net.Server to also listen on the unspecified IPv4 address\n(0.0.0.0).
Opposite of unref(), calling ref() on a previously unrefed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is refed calling ref() again will have no effect.
unref()
ref()
unref
ref
Calling unref() on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefed calling\nunref() again will have no effect.
Set this property to reject connections when the server's connection count gets\nhigh.
It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().
child_process.fork()
net.Server is an EventEmitter with the following events:
EventEmitter
This class is an abstraction of a TCP socket or a streaming IPC endpoint\n(uses named pipes on Windows, and Unix domain sockets otherwise). It is also\nan EventEmitter.
A net.Socket can be created by the user and used directly to interact with\na server. For example, it is returned by net.createConnection(),\nso the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection\nis received. For example, it is passed to the listeners of a\n'connection' event emitted on a net.Server, so the user can use\nit to interact with the client.
'connection'
Emitted once the socket is fully closed. The argument hadError is a boolean\nwhich says if the socket was closed due to a transmission error.
hadError
Emitted when a socket connection is successfully established.\nSee net.createConnection().
Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().
Buffer
String
socket.setEncoding()
The data will be lost if there is no listener when a Socket\nemits a 'data' event.
Socket
'data'
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values of socket.write().
socket.write()
Emitted when the other end of the socket signals the end of transmission, thus\nending the readable side of the socket.
By default (allowHalfOpen is false) the socket will send an end of\ntransmission packet back and destroy its file descriptor once it has written out\nits pending write queue. However, if allowHalfOpen is set to true, the\nsocket will not automatically end() its writable side,\nallowing the user to write arbitrary amounts of data. The user must call\nend() explicitly to close the connection (i.e. sending a\nFIN packet back).
allowHalfOpen
end()
Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.
Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.
dns.lookup()
Emitted when a socket is ready to be used.
Triggered immediately after 'connect'.
'connect'
Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.
See also: socket.setTimeout().
socket.setTimeout()
Returns the bound address, the address family name and port of the\nsocket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
Initiate a connection on a given socket.
socket.connect(options[, connectListener])
socket.connect(path[, connectListener])
socket.connect(port[, host][, connectListener])
This function is asynchronous. When the connection is established, the\n'connect' event will be emitted. If there is a problem connecting,\ninstead of a 'connect' event, an 'error' event will be emitted with\nthe error passed to the 'error' listener.\nThe last parameter connectListener, if supplied, will be added as a listener\nfor the 'connect' event once.
'error'
connectListener
This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.
Initiate a connection on a given socket. Normally this method is not needed,\nthe socket should be created and opened with net.createConnection(). Use\nthis only when implementing a custom Socket.
For TCP connections, available options are:
options
'localhost'
4
6
0
hints
lookup
noDelay
keepAlive
socket.setKeepAlive([enable][, initialDelay])
keepAliveInitialDelay
For IPC connections, available options are:
For both types, available options include:
onread
buffer
'end'
pause()
resume()
Following is an example of a client using the onread option:
const net = require('node:net');\nnet.connect({\n port: 80,\n onread: {\n // Reuses a 4KiB Buffer for every read from the socket.\n buffer: Buffer.alloc(4 * 1024),\n callback: function(nread, buf) {\n // Received data is available in `buf` from 0 to `nread`.\n console.log(buf.toString('utf8', 0, nread));\n }\n }\n});\n
Initiate an IPC connection on the given socket.
Alias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.
{ path: path }
Initiate a TCP connection on the given socket.
Alias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.
{port: port, host: host}
Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.
See writable.destroy() for further details.
writable.destroy()
Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.
See writable.end() for further details.
writable.end()
Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.
Opposite of unref(), calling ref() on a previously unrefed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is refed calling ref again will have no effect.
Close the TCP connection by sending an RST packet and destroy the stream.\nIf this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.\nOtherwise, it will call socket.destroy with an ERR_SOCKET_CLOSED Error.\nIf this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE Error.
socket.destroy
ERR_SOCKET_CLOSED
ERR_INVALID_HANDLE_TYPE
Resumes reading after a call to socket.pause().
socket.pause()
Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.
readable.setEncoding()
Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.
Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting.
initialDelay
Enabling the keep-alive functionality will set the following socket options:
SO_KEEPALIVE=1
TCP_KEEPIDLE=initialDelay
TCP_KEEPCNT=10
TCP_KEEPINTVL=1
Enable/disable the use of Nagle's algorithm.
When a TCP connection is created, it will have Nagle's algorithm enabled.
Nagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.
Passing true for noDelay or not passing an argument will disable Nagle's\nalgorithm for the socket. Passing false for noDelay will enable Nagle's\nalgorithm.
Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.
timeout
When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually call\nsocket.end() or socket.destroy() to end the connection.
'timeout'
socket.end()
socket.destroy()
socket.setTimeout(3000);\nsocket.on('timeout', () => {\n console.log('socket timeout');\n socket.end();\n});\n
If timeout is 0, then the existing idle timeout is disabled.
The optional callback parameter will be added as a one-time listener for the\n'timeout' event.
Calling unref() on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefed calling\nunref() again will have no effect.
Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.
'drain'
The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.
See Writable stream write() method for more\ninformation.
Writable
write()
This property shows the number of characters buffered for writing. The buffer\nmay contain strings whose length after encoding is not yet known. So this number\nis only an approximation of the number of bytes in the buffer.
net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket. The network connection\nsimply might be too slow. Node.js will internally queue up the data written to a\nsocket and send it out over the wire when it is possible.
The consequence of this internal buffering is that memory may grow.\nUsers who experience large or growing bufferSize should attempt to\n\"throttle\" the data flows in their program with\nsocket.pause() and socket.resume().
bufferSize
socket.resume()
The amount of received bytes.
The amount of bytes sent.
If true,\nsocket.connect(options[, connectListener]) was\ncalled and has not yet finished. It will stay true until the socket becomes\nconnected, then it is set to false and the 'connect' event is emitted. Note\nthat the\nsocket.connect(options[, connectListener])\ncallback is a listener for the 'connect' event.
See writable.destroyed for further details.
writable.destroyed
The string representation of the local IP address the remote client is\nconnecting on. For example, in a server listening on '0.0.0.0', if a client\nconnects on '192.168.1.1', the value of socket.localAddress would be\n'192.168.1.1'.
'0.0.0.0'
'192.168.1.1'
socket.localAddress
The numeric representation of the local port. For example, 80 or 21.
80
21
The string representation of the local IP family. 'IPv4' or 'IPv6'.
This is true if the socket is not connected yet, either because .connect()\nhas not yet been called or because it is still in the process of connecting\n(see socket.connecting).
.connect()
socket.connecting
The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
'74.125.127.100'
'2001:4860:a005::68'
The string representation of the remote IP family. 'IPv4' or 'IPv6'.
The numeric representation of the remote port. For example, 80 or 21.
The socket timeout in milliseconds as set by socket.setTimeout().\nIt is undefined if a timeout has not been set.
This property represents the state of the connection as a string.
socket.readyState
opening
open
readOnly
writeOnly
Creates a new socket object.
The newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.
connect()
Aliases to\nnet.createConnection().
net.connect(options[, connectListener])
net.connect(path[, connectListener])
net.connect(port[, host][, connectListener])
Alias to\nnet.createConnection(options[, connectListener]).
net.createConnection(options[, connectListener])
Alias to\nnet.createConnection(path[, connectListener]).
net.createConnection(path[, connectListener])
Alias to\nnet.createConnection(port[, host][, connectListener]).
net.createConnection(port[, host][, connectListener])
A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.
When the connection is established, a 'connect' event will be emitted\non the returned socket. The last parameter connectListener, if supplied,\nwill be added as a listener for the 'connect' event once.
The net.connect() function is an alias to this function.
For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).
new net.Socket([options])
Additional options:
socket.setTimeout(timeout)
Following is an example of a client of the echo server described\nin the net.createServer() section:
const net = require('node:net');\nconst client = net.createConnection({ port: 8124 }, () => {\n // 'connect' listener.\n console.log('connected to server!');\n client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n console.log(data.toString());\n client.end();\n});\nclient.on('end', () => {\n console.log('disconnected from server');\n});\n
To connect on the socket /tmp/echo.sock:
/tmp/echo.sock
const client = net.createConnection({ path: '/tmp/echo.sock' });\n
Initiates an IPC connection.
This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(path[, connectListener]),\nthen returns the net.Socket that starts the connection.
Initiates a TCP connection.
This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(port[, host][, connectListener]),\nthen returns the net.Socket that starts the connection.
Creates a new TCP or IPC server.
If allowHalfOpen is set to true, when the other end of the socket\nsignals the end of transmission, the server will only send back the end of\ntransmission when socket.end() is explicitly called. For example, in the\ncontext of TCP, when a FIN packed is received, a FIN packed is sent\nback only when socket.end() is explicitly called. Until then the\nconnection is half-closed (non-readable but still writable). See 'end'\nevent and RFC 1122 (section 4.2.2.13) for more information.
If pauseOnConnect is set to true, then the socket associated with each\nincoming connection will be paused, and no data will be read from its handle.\nThis allows connections to be passed between processes without any data being\nread by the original process. To begin reading data from a paused socket, call\nsocket.resume().
pauseOnConnect
The server can be a TCP server or an IPC server, depending on what it\nlisten() to.
Here is an example of a TCP echo server which listens for connections\non port 8124:
const net = require('node:net');\nconst server = net.createServer((c) => {\n // 'connection' listener.\n console.log('client connected');\n c.on('end', () => {\n console.log('client disconnected');\n });\n c.write('hello\\r\\n');\n c.pipe(c);\n});\nserver.on('error', (err) => {\n throw err;\n});\nserver.listen(8124, () => {\n console.log('server bound');\n});\n
Test this by using telnet:
telnet
$ telnet localhost 8124\n
To listen on the socket /tmp/echo.sock:
server.listen('/tmp/echo.sock', () => {\n console.log('server bound');\n});\n
Use nc to connect to a Unix domain socket server:
nc
$ nc -U /tmp/echo.sock\n
Returns 6 if input is an IPv6 address. Returns 4 if input is an IPv4\naddress in dot-decimal notation with no leading zeroes. Otherwise, returns\n0.
input
net.isIP('::1'); // returns 6\nnet.isIP('127.0.0.1'); // returns 4\nnet.isIP('127.000.000.001'); // returns 0\nnet.isIP('127.0.0.1/24'); // returns 0\nnet.isIP('fhqwhgads'); // returns 0\n
Returns true if input is an IPv4 address in dot-decimal notation with no\nleading zeroes. Otherwise, returns false.
net.isIPv4('127.0.0.1'); // returns true\nnet.isIPv4('127.000.000.001'); // returns false\nnet.isIPv4('127.0.0.1/24'); // returns false\nnet.isIPv4('fhqwhgads'); // returns false\n
Returns true if input is an IPv6 address. Otherwise, returns false.
net.isIPv6('::1'); // returns true\nnet.isIPv6('fhqwhgads'); // returns false\n