Net | Node.js v21.7.3 Documentation
https://nodejs.org/docs/latest-v21.x/api/net.html • 154 KB fetched
Open original page
Net | Node.js v21.7.3 Documentation
Node.js
* About this documentation
* Usage and example
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Corepack
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
Node.js v21.7.3 documentation
* Node.js v21.7.3
*
► ▼
Table of contents
* Net
* IPC support
* Identifying paths for IPC connections
* Class: net.BlockList
* blockList.addAddress(address[, type])
* blockList.addRange(start, end[, type])
* blockList.addSubnet(net, prefix[, type])
* blockList.check(address[, type])
* blockList.rules
* Class: net.SocketAddress
* new net.SocketAddress([options])
* socketaddress.address
* socketaddress.family
* socketaddress.flowlabel
* socketaddress.port
* Class: net.Server
* new net.Server([options][, connectionListener])
* Event: 'close'
* Event: 'connection'
* Event: 'error'
* Event: 'listening'
* Event: 'drop'
* server.address()
* server.close([callback])
* server[Symbol.asyncDispose]()
* server.getConnections(callback)
* server.listen()
* server.listen(handle[, backlog][, callback])
* server.listen(options[, callback])
* server.listen(path[, backlog][, callback])
* server.listen([port[, host[, backlog]]][, callback])
* server.listening
* server.maxConnections
* server.ref()
* server.unref()
* Class: net.Socket
* new net.Socket([options])
* Event: 'close'
* Event: 'connect'
* Event: 'connectionAttempt'
* Event: 'connectionAttemptFailed'
* Event: 'connectionAttemptTimeout'
* Event: 'data'
* Event: 'drain'
* Event: 'end'
* Event: 'error'
* Event: 'lookup'
* Event: 'ready'
* Event: 'timeout'
* socket.address()
* socket.autoSelectFamilyAttemptedAddresses
* socket.bufferSize
* socket.bytesRead
* socket.bytesWritten
* socket.connect()
* socket.connect(options[, connectListener])
* socket.connect(path[, connectListener])
* socket.connect(port[, host][, connectListener])
* socket.connecting
* socket.destroy([error])
* socket.destroyed
* socket.destroySoon()
* socket.end([data[, encoding]][, callback])
* socket.localAddress
* socket.localPort
* socket.localFamily
* socket.pause()
* socket.pending
* socket.ref()
* socket.remoteAddress
* socket.remoteFamily
* socket.remotePort
* socket.resetAndDestroy()
* socket.resume()
* socket.setEncoding([encoding])
* socket.setKeepAlive([enable][, initialDelay])
* socket.setNoDelay([noDelay])
* socket.setTimeout(timeout[, callback])
* socket.timeout
* socket.unref()
* socket.write(data[, encoding][, callback])
* socket.readyState
* net.connect()
* net.connect(options[, connectListener])
* net.connect(path[, connectListener])
* net.connect(port[, host][, connectListener])
* net.createConnection()
* net.createConnection(options[, connectListener])
* net.createConnection(path[, connectListener])
* net.createConnection(port[, host][, connectListener])
* net.createServer([options][, connectionListener])
* net.getDefaultAutoSelectFamily()
* net.setDefaultAutoSelectFamily(value)
* net.getDefaultAutoSelectFamilyAttemptTimeout()
* net.setDefaultAutoSelectFamilyAttemptTimeout(value)
* net.isIP(input)
* net.isIPv4(input)
* net.isIPv6(input)
*
► ▼
Index
* About this documentation
* Usage and example
*
Index
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Corepack
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
*
► ▼
Other versions
* 21.x
* 20.x LTS
* 19.x
* 18.x LTS
* 17.x
* 16.x
* 15.x
* 14.x
* 13.x
* 12.x
* 11.x
* 10.x
* 9.x
* 8.x
* 7.x
* 6.x
* 5.x
* 4.x
* 0.12.x
* 0.10.x
*
► ▼
Options
*
View on single page
*
View as JSON
* Edit on GitHub
Table of contents
* Net
* IPC support
* Identifying paths for IPC connections
* Class: net.BlockList
* blockList.addAddress(address[, type])
* blockList.addRange(start, end[, type])
* blockList.addSubnet(net, prefix[, type])
* blockList.check(address[, type])
* blockList.rules
* Class: net.SocketAddress
* new net.SocketAddress([options])
* socketaddress.address
* socketaddress.family
* socketaddress.flowlabel
* socketaddress.port
* Class: net.Server
* new net.Server([options][, connectionListener])
* Event: 'close'
* Event: 'connection'
* Event: 'error'
* Event: 'listening'
* Event: 'drop'
* server.address()
* server.close([callback])
* server[Symbol.asyncDispose]()
* server.getConnections(callback)
* server.listen()
* server.listen(handle[, backlog][, callback])
* server.listen(options[, callback])
* server.listen(path[, backlog][, callback])
* server.listen([port[, host[, backlog]]][, callback])
* server.listening
* server.maxConnections
* server.ref()
* server.unref()
* Class: net.Socket
* new net.Socket([options])
* Event: 'close'
* Event: 'connect'
* Event: 'connectionAttempt'
* Event: 'connectionAttemptFailed'
* Event: 'connectionAttemptTimeout'
* Event: 'data'
* Event: 'drain'
* Event: 'end'
* Event: 'error'
* Event: 'lookup'
* Event: 'ready'
* Event: 'timeout'
* socket.address()
* socket.autoSelectFamilyAttemptedAddresses
* socket.bufferSize
* socket.bytesRead
* socket.bytesWritten
* socket.connect()
* socket.connect(options[, connectListener])
* socket.connect(path[, connectListener])
* socket.connect(port[, host][, connectListener])
* socket.connecting
* socket.destroy([error])
* socket.destroyed
* socket.destroySoon()
* socket.end([data[, encoding]][, callback])
* socket.localAddress
* socket.localPort
* socket.localFamily
* socket.pause()
* socket.pending
* socket.ref()
* socket.remoteAddress
* socket.remoteFamily
* socket.remotePort
* socket.resetAndDestroy()
* socket.resume()
* socket.setEncoding([encoding])
* socket.setKeepAlive([enable][, initialDelay])
* socket.setNoDelay([noDelay])
* socket.setTimeout(timeout[, callback])
* socket.timeout
* socket.unref()
* socket.write(data[, encoding][, callback])
* socket.readyState
* net.connect()
* net.connect(options[, connectListener])
* net.connect(path[, connectListener])
* net.connect(port[, host][, connectListener])
* net.createConnection()
* net.createConnection(options[, connectListener])
* net.createConnection(path[, connectListener])
* net.createConnection(port[, host][, connectListener])
* net.createServer([options][, connectionListener])
* net.getDefaultAutoSelectFamily()
* net.setDefaultAutoSelectFamily(value)
* net.getDefaultAutoSelectFamilyAttemptTimeout()
* net.setDefaultAutoSelectFamilyAttemptTimeout(value)
* net.isIP(input)
* net.isIPv4(input)
* net.isIPv6(input)
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:
const net = require ( 'node:net' ); copy
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 gets truncated to an OS-dependent length of
sizeof(sockaddr_un.sun_path) - 1 . 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' )); copy
Class: net.BlockList #
Added in: v15.0.0, v14.18.0
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]) #
Added in: v15.0.0, v14.18.0
* address <string> | <net.SocketAddress> An IPv4 or IPv6 address.
* type <string> Either 'ipv4' or 'ipv6' . Default: 'ipv4' .
Adds a rule to block the given IP address.
blockList.addRange(start, end[, type]) #
Added in: v15.0.0, v14.18.0
* start <string> | <net.SocketAddress> The starting IPv4 or IPv6 address in the
range.
* end <string> | <net.SocketAddress> The ending IPv4 or IPv6 address in the range.
* type <string> Either 'ipv4' or 'ipv6' . Default: 'ipv4' .
Adds a rule to block a range of IP addresses from start (inclusive) to
end (inclusive).
blockList.addSubnet(net, prefix[, type]) #
Added in: v15.0.0, v14.18.0
* 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]) #
Added in: v15.0.0, v14.18.0
* address <string> | <net.SocketAddress> The IP address to check
* type <string> Either 'ipv4' or 'ipv6' . Default: 'ipv4' .
* Returns: <boolean>
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 copy
blockList.rules #
Added in: v15.0.0, v14.18.0
* Type: <string[]>
The list of rules added to the blocklist.
Class: net.SocketAddress #
Added in: v15.14.0, v14.18.0
new net.SocketAddress([options]) #
Added in: v15.14.0, v14.18.0
* 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 #
Added in: v15.14.0, v14.18.0
* Type <string>
socketaddress.family #
Added in: v15.14.0, v14.18.0
* Type <string> Either 'ipv4' or 'ipv6' .
socketaddress.flowlabel #
Added in: v15.14.0, v14.18.0
* Type <number>
socketaddress.port #
Added in: v15.14.0, v14.18.0
* Type <number>
Class: net.Server #
Added in: v0.1.90
* Extends: <EventEmitter>
This class is used to create a TCP or IPC server.
new net.Server([options][, connectionListener]) #
* options <Object> See
net.createServer([options][, connectionListener]) .
* connectionListener <Function> Automatically set as a listener for the
'connection' event.
* Returns: <net.Server>
net.Server is an EventEmitter with the following events:
Event: 'close' #
Added in: v0.5.0
Emitted when the server closes. If connections exist, this
event is not emitted until all connections are ended.
Event: 'connection' #
Added in: v0.1.90
* <net.Socket> The connection object
Emitted when a new connection is made. socket is an instance of
net.Socket .
Event: 'error' #
Added in: v0.1.90
* <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' #
Added in: v0.1.90
Emitted when the server has been bound after calling server.listen() .
Event: 'drop' #
Added in: v18.6.0, v16.17.0
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.
* localAddress <string> Local address.
* localPort <number> Local port.
* localFamily <string> Local family.
* remoteAddress <string> Remote address.
* remotePort <number> Remote port.
* remoteFamily <string> Remote IP family. 'IPv4' or 'IPv6' .
server.address() #
History
Version Changes
v18.4.0
The family property now returns a string instead of a number.
v18.0.0
The family property now returns a number instead of a string.
v0.1.90
Added in: v0.1.90
* Returns: <Object> | <string> | <null>
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 ());
}); copy
server.address() returns null before the 'listening' event has been
emitted or after calling server.close() .
server.close([callback]) #
Added in: v0.1.90
* callback <Function> Called when the server is closed.
* Returns: <net.Server>
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]() #
Added in: v20.5.0, v18.18.0
Stability: 1 - Experimental
Calls server.close() and returns a promise that fulfills when the
server has closed.
server.getConnections(callback) #
Added in: v0.9.7
* callback <Function>
* Returns: <net.Server>
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:
* server.listen(handle[, backlog][, callback])
* server.listen(options[, callback])
* server.listen(path[, backlog][, callback])
for IPC servers
* server.listen([port[, host[, backlog]]][, callback])
for TCP servers
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
Links found on this page
- Node.js [direct]
- About this documentation [direct]
- Usage and example [direct]
- Assertion testing [direct]
- Asynchronous context tracking [direct]
- Async hooks [direct]
- Buffer [direct]
- C++ addons [direct]
- C/C++ addons with Node-API [direct]
- C++ embedder API [direct]
- Child processes [direct]
- Cluster [direct]
- Command-line options [direct]
- Console [direct]
- Corepack [direct]
- Crypto [direct]
- Debugger [direct]
- Deprecated APIs [direct]
- Diagnostics Channel [direct]
- DNS [direct]
- Domain [direct]
- Errors [direct]
- Events [direct]
- File system [direct]
- Globals [direct]
- HTTP [direct]
- HTTP/2 [direct]
- HTTPS [direct]
- Inspector [direct]
- Internationalization [direct]
- Modules: CommonJS modules [direct]
- Modules: ECMAScript modules [direct]
- Modules: node:module API [direct]
- Modules: Packages [direct]
- Net [direct]
- OS [direct]
- Path [direct]
- Performance hooks [direct]
- Permissions [direct]
- Process [direct]
- Punycode [direct]
- Query strings [direct]
- Readline [direct]
- REPL [direct]
- Report [direct]
- Single executable applications [direct]
- Stream [direct]
- String decoder [direct]
- Test runner [direct]
- Timers [direct]
- TLS/SSL [direct]
- Trace events [direct]
- TTY [direct]
- UDP/datagram [direct]
- URL [direct]
- Utilities [direct]
- V8 [direct]
- VM [direct]
- WASI [direct]
- Web Crypto API [direct]
- Web Streams API [direct]
- Worker threads [direct]
- Zlib [direct]
- Code repository and issue tracker [direct]
- Index [direct]
- 20.x LTS [direct]
- 19.x [direct]
- 18.x LTS [direct]
- 17.x [direct]
- 16.x [direct]
- 15.x [direct]
- 14.x [direct]
- 13.x [direct]
- 12.x [direct]
- 11.x [direct]
- 10.x [direct]
- 9.x [direct]
- 8.x [direct]
- 7.x [direct]
- 6.x [direct]