Net#
Source Code:lib/net.js
Thenode:net
module provides an asynchronous network API for creating stream-basedTCP orIPC servers (net.createServer()
) and clients(net.createConnection()
).
It can be accessed using:
import netfrom'node:net';
const net =require('node:net');
IPC support#
History
Version | Changes |
---|---|
v20.8.0 | Support binding to abstract Unix domain socket path like |
Thenode:net
module supports IPC with named pipes on Windows, and Unix domainsockets on other operating systems.
Identifying paths for IPC connections#
net.connect()
,net.createConnection()
,server.listen()
, andsocket.connect()
take apath
parameter to identify IPC endpoints.
On Unix, the local domain is also known as the Unix domain. The path is afile system pathname. It will throw an error when the length of pathname isgreater than the length ofsizeof(sockaddr_un.sun_path)
. Typical values are107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction createsthe Unix domain socket, it will unlink the Unix domain socket as well. Forexample,net.createServer()
may create a Unix domain socket andserver.close()
will unlink it. But if a user creates the Unix domainsocket outside of these abstractions, the user will need to remove it. The sameapplies when a Node.js API creates a Unix domain socket but the program thencrashes. In short, a Unix domain socket will be visible in the file system andwill 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 Unixabstract socket is not visible in the file system and it will disappear automaticallywhen all open references to the socket are closed.
On Windows, the local domain is implemented using a named pipe. The pathmustrefer 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 willnot persist. They are removed when the last reference to them is closed.Unlike Unix domain sockets, Windows will close and remove the pipe when theowning process exits.
JavaScript string escaping requires paths to be specified with extra backslashescaping such as:
net.createServer().listen( path.join('\\\\?\\pipe', process.cwd(),'myctl'));
Class:net.BlockList
#
TheBlockList
object can be used with some network APIs to specify rules fordisabling inbound or outbound access to specific IP addresses, IP ranges, orIP subnets.
blockList.addAddress(address[, type])
#
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])
#
start
<string> |<net.SocketAddress> The starting IPv4 or IPv6 address in therange.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 fromstart
(inclusive) toend
(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, thismust be a value between0
and32
. For IPv6, this must be between0
and128
.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])
#
address
<string> |<net.SocketAddress> The IP address to checktype
<string> Either'ipv4'
or'ipv6'
.Default:'ipv4'
.- Returns:<boolean>
Returnstrue
if the given IP address matches any of the rules added to theBlockList
.
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: trueconsole.log(blockList.check('10.0.0.3'));// Prints: trueconsole.log(blockList.check('222.111.111.222'));// Prints: false// IPv6 notation for IPv4 addresses works:console.log(blockList.check('::ffff:7b7b:7b7b','ipv6'));// Prints: trueconsole.log(blockList.check('::ffff:123.123.123.123','ipv6'));// Prints: true
Class:net.SocketAddress
#
new net.SocketAddress([options])
#
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 returnsundefined
.
Class:net.Server
#
- Extends:<EventEmitter>
This class is used to create a TCP orIPC server.
new net.Server([options][, connectionListener])
#
options
<Object> Seenet.createServer([options][, connectionListener])
.connectionListener
<Function> Automatically set as a listener for the'connection'
event.- Returns:<net.Server>
net.Server
is anEventEmitter
with the following events:
Event:'close'
#
Emitted when the server closes. If connections exist, thisevent is not emitted until all connections are ended.
Event:'connection'
#
- <net.Socket> The connection object
Emitted when a new connection is made.socket
is an instance ofnet.Socket
.
Event:'error'
#
Emitted when an error occurs. Unlikenet.Socket
, the'close'
event willnot be emitted directly following this event unlessserver.close()
is manually called. See the example in discussion ofserver.listen()
.
Event:'listening'
#
Emitted when the server has been bound after callingserver.listen()
.
Event:'drop'
#
When the number of connections reaches the threshold ofserver.maxConnections
,the server will drop new connections and emit'drop'
event instead. If it is aTCP server, the argument is as follows, otherwise the argument isundefined
.
server.address()
#
History
Version | Changes |
---|---|
v18.4.0 | The |
v18.0.0 | The |
v0.1.90 | Added in: v0.1.90 |
Returns the boundaddress
, the addressfamily
name, andport
of the serveras 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 returnedas 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()
returnsnull
before the'listening'
event has beenemitted or after callingserver.close()
.
server.close([callback])
#
callback
<Function> Called when the server is closed.- Returns:<net.Server>
Stops the server from accepting new connections and keeps existingconnections. This function is asynchronous, the server is finally closedwhen all connections are ended and the server emits a'close'
event.The optionalcallback
will be called once the'close'
event occurs. Unlikethat event, it will be called with anError
as its only argument if the serverwas not open when it was closed.
server[Symbol.asyncDispose]()
#
History
Version | Changes |
---|---|
v24.2.0 | No longer experimental. |
v20.5.0, v18.18.0 | Added in: v20.5.0, v18.18.0 |
Callsserver.close()
and returns a promise that fulfills when theserver has closed.
server.getConnections(callback)
#
callback
<Function>- Returns:<net.Server>
Asynchronously get the number of concurrent connections on the server. Workswhen sockets were sent to forks.
Callback should take two argumentserr
andcount
.
server.listen()
#
Start a server listening for connections. Anet.Server
can be a TCP oranIPC server depending on what it listens to.
Possible signatures:
server.listen(handle[, backlog][, callback])
server.listen(options[, callback])
server.listen(path[, backlog][, callback])
forIPC serversserver.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 parametercallback
will be added as a listener for the'listening'
event.
Alllisten()
methods can take abacklog
parameter to specify the maximumlength of the queue of pending connections. The actual length will be determinedby the OS through sysctl settings such astcp_max_syn_backlog
andsomaxconn
on Linux. The default value of this parameter is 511 (not 512).
Allnet.Socket
are set toSO_REUSEADDR
(seesocket(7)
fordetails).
Theserver.listen()
method can be called again if and only if there was anerror during the firstserver.listen()
call orserver.close()
has beencalled. Otherwise, anERR_SERVER_ALREADY_LISTEN
error will be thrown.
One of the most common errors raised when listening isEADDRINUSE
.This happens when another server is already listening on the requestedport
/path
/handle
. One way to handle this would be to retryafter 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])
#
handle
<Object>backlog
<number> Common parameter ofserver.listen()
functionscallback
<Function>- Returns:<net.Server>
Start a server listening for connections on a givenhandle
that hasalready been bound to a port, a Unix domain socket, or a Windows named pipe.
Thehandle
object can be either a server, a socket (anything with anunderlying_handle
member), or an object with anfd
member that is avalid file descriptor.
Listening on a file descriptor is not supported on Windows.
server.listen(options[, callback])
#
History
Version | Changes |
---|---|
v23.1.0, v22.12.0 | The |
v15.6.0 | AbortSignal support was added. |
v11.4.0 | The |
v0.11.14 | Added in: v0.11.14 |
options
<Object> Required. Supports the following properties:backlog
<number> Common parameter ofserver.listen()
functions.exclusive
<boolean>Default:false
host
<string>ipv6Only
<boolean> For TCP servers, settingipv6Only
totrue
willdisable dual-stack support, i.e., binding to host::
won't make0.0.0.0
be bound.Default:false
.reusePort
<boolean> For TCP servers, settingreusePort
totrue
allowsmultiple sockets on the same host to bind to the same port. Incoming connectionsare distributed by the operating system to listening sockets. This option isavailable 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 ifport
is specified. SeeIdentifying paths for IPC connections.port
<number>readableAll
<boolean> For IPC servers makes the pipe readablefor all users.Default:false
.signal
<AbortSignal> An AbortSignal that may be used to close a listeningserver.writableAll
<boolean> For IPC servers makes the pipe writablefor all users.Default:false
.
callback
<Function>functions.- Returns:<net.Server>
Ifport
is specified, it behaves the same asserver.listen([port[, host[, backlog]]][, callback])
.Otherwise, ifpath
is specified, it behaves the same asserver.listen(path[, backlog][, callback])
.If none of them is specified, an error will be thrown.
Ifexclusive
isfalse
(default), then cluster workers will use the sameunderlying handle, allowing connection handling duties to be shared. Whenexclusive
istrue
, the handle is not shared, and attempted port sharingresults in an error. An example which listens on an exclusive port isshown below.
server.listen({host:'localhost',port:80,exclusive:true,});
Whenexclusive
istrue
and the underlying handle is shared, it ispossible that several workers query a handle with different backlogs.In this case, the firstbacklog
passed to the master process will be used.
Starting an IPC server as root may cause the server path to be inaccessible forunprivileged users. UsingreadableAll
andwritableAll
will make the serveraccessible for all users.
If thesignal
option is enabled, calling.abort()
on the correspondingAbortController
is similar to calling.close()
on the server:
const controller =newAbortController();server.listen({host:'localhost',port:80,signal: controller.signal,});// Later, when you want to close the server.controller.abort();
server.listen(path[, backlog][, callback])
#
path
<string> Path the server should listen to. SeeIdentifying paths for IPC connections.backlog
<number> Common parameter ofserver.listen()
functions.callback
<Function>.- Returns:<net.Server>
Start anIPC server listening for connections on the givenpath
.
server.listen([port[, host[, backlog]]][, callback])
#
port
<number>host
<string>backlog
<number> Common parameter ofserver.listen()
functions.callback
<Function>.- Returns:<net.Server>
Start a TCP server listening for connections on the givenport
andhost
.
Ifport
is omitted or is 0, the operating system will assign an arbitraryunused port, which can be retrieved by usingserver.address().port
after the'listening'
event has been emitted.
Ifhost
is omitted, the server will accept connections on theunspecified IPv6 address (::
) when IPv6 is available, or theunspecified IPv4 address (0.0.0.0
) otherwise.
In most operating systems, listening to theunspecified IPv6 address (::
)may cause thenet.Server
to also listen on theunspecified IPv4 address(0.0.0.0
).
server.listening
#
- <boolean> Indicates whether or not the server is listening for connections.
server.maxConnections
#
History
Version | Changes |
---|---|
v21.0.0 | Setting |
v0.2.0 | Added in: v0.2.0 |
When the number of connections reaches theserver.maxConnections
threshold:
If the process is not running in cluster mode, Node.js will close the connection.
If the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set [
server.dropMaxConnection
][] totrue
.
It is not recommended to use this option once a socket has been sent to a childwithchild_process.fork()
.
server.dropMaxConnection
#
Set this property totrue
to begin closing connections once the number of connections reaches the [server.maxConnections
][] threshold. This setting is only effective in cluster mode.
server.ref()
#
- Returns:<net.Server>
Opposite ofunref()
, callingref()
on a previouslyunref
ed server willnot let the program exit if it's the only server left (the default behavior).If the server isref
ed callingref()
again will have no effect.
server.unref()
#
- Returns:<net.Server>
Callingunref()
on a server will allow the program to exit if this is the onlyactive server in the event system. If the server is alreadyunref
ed callingunref()
again will have no effect.
Class:net.Socket
#
- Extends:<stream.Duplex>
This class is an abstraction of a TCP socket or a streamingIPC endpoint(uses named pipes on Windows, and Unix domain sockets otherwise). It is alsoanEventEmitter
.
Anet.Socket
can be created by the user and used directly to interact witha server. For example, it is returned bynet.createConnection()
,so 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 connectionis received. For example, it is passed to the listeners of a'connection'
event emitted on anet.Server
, so the user can useit to interact with the client.
new net.Socket([options])
#
History
Version | Changes |
---|---|
v15.14.0 | AbortSignal support was added. |
v12.10.0 | Added |
v0.3.4 | Added in: v0.3.4 |
options
<Object> Available options are:allowHalfOpen
<boolean> If set tofalse
, then the socket willautomatically end the writable side when the readable side ends. Seenet.createServer()
and the'end'
event for details.Default:false
.fd
<number> If specified, wrap around an existing socket withthe given file descriptor, otherwise a new socket will be created.onread
<Object> If specified, incoming data is stored in a singlebuffer
and passed to the suppliedcallback
when data arrives on the socket.This will cause the streaming functionality to not provide any data.The socket will emit events like'error'
,'end'
, and'close'
as usual. Methods likepause()
andresume()
will also behave asexpected.buffer
<Buffer> |<Uint8Array> |<Function> Either a reusable chunk of memory touse for storing incoming data or a function that returns such.callback
<Function> This function is called for every chunk of incomingdata. Two arguments are passed to it: the number of bytes written tobuffer
and a reference tobuffer
. Returnfalse
from this function toimplicitlypause()
the socket. This function will be executed in theglobal context.
readable
<boolean> Allow reads on the socket when anfd
is passed,otherwise ignored.Default:false
.signal
<AbortSignal> An Abort signal that may be used to destroy thesocket.writable
<boolean> Allow writes on the socket when anfd
is passed,otherwise ignored.Default:false
.
- Returns:<net.Socket>
Creates a new socket object.
The newly created socket can be either a TCP socket or a streamingIPCendpoint, depending on what itconnect()
to.
Event:'close'
#
hadError
<boolean>true
if the socket had a transmission error.
Emitted once the socket is fully closed. The argumenthadError
is a booleanwhich says if the socket was closed due to a transmission error.
Event:'connect'
#
Emitted when a socket connection is successfully established.Seenet.createConnection()
.
Event:'connectionAttempt'
#
ip
<string> The IP which the socket is attempting to connect to.port
<number> The port which the socket is attempting to connect to.family
<number> The family of the IP. It can be6
for IPv6 or4
for IPv4.
Emitted when a new connection attempt is started. This may be emitted multiple timesif the family autoselection algorithm is enabled insocket.connect(options)
.
Event:'connectionAttemptFailed'
#
ip
<string> The IP which the socket attempted to connect to.port
<number> The port which the socket attempted to connect to.family
<number> The family of the IP. It can be6
for IPv6 or4
for IPv4.error
<Error> The error associated with the failure.
Emitted when a connection attempt failed. This may be emitted multiple timesif the family autoselection algorithm is enabled insocket.connect(options)
.
Event:'connectionAttemptTimeout'
#
ip
<string> The IP which the socket attempted to connect to.port
<number> The port which the socket attempted to connect to.family
<number> The family of the IP. It can be6
for IPv6 or4
for IPv4.
Emitted when a connection attempt timed out. This is only emitted (and may beemitted multiple times) if the family autoselection algorithm is enabledinsocket.connect(options)
.
Event:'data'
#
Emitted when data is received. The argumentdata
will be aBuffer
orString
. Encoding of data is set bysocket.setEncoding()
.
The data will be lost if there is no listener when aSocket
emits a'data'
event.
Event:'drain'
#
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values ofsocket.write()
.
Event:'end'
#
Emitted when the other end of the socket signals the end of transmission, thusending the readable side of the socket.
By default (allowHalfOpen
isfalse
) the socket will send an end oftransmission packet back and destroy its file descriptor once it has written outits pending write queue. However, ifallowHalfOpen
is set totrue
, thesocket will not automaticallyend()
its writable side,allowing the user to write arbitrary amounts of data. The user must callend()
explicitly to close the connection (i.e. sending aFIN packet back).
Event:'error'
#
Emitted when an error occurs. The'close'
event will be called directlyfollowing this event.
Event:'lookup'
#
History
Version | Changes |
---|---|
v5.10.0 | The |
v0.11.3 | Added in: v0.11.3 |
Emitted after resolving the host name but before connecting.Not applicable to Unix sockets.
err
<Error> |<null> The error object. Seedns.lookup()
.address
<string> The IP address.family
<number> |<null> The address type. Seedns.lookup()
.host
<string> The host name.
Event:'ready'
#
Emitted when a socket is ready to be used.
Triggered immediately after'connect'
.
Event:'timeout'
#
Emitted if the socket times out from inactivity. This is only to notify thatthe socket has been idle. The user must manually close the connection.
See also:socket.setTimeout()
.
socket.address()
#
History
Version | Changes |
---|---|
v18.4.0 | The |
v18.0.0 | The |
v0.1.90 | Added in: v0.1.90 |
- Returns:<Object>
Returns the boundaddress
, the addressfamily
name andport
of thesocket as reported by the operating system:{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
socket.autoSelectFamilyAttemptedAddresses
#
This property is only present if the family autoselection algorithm is enabled insocket.connect(options)
and it is an array of the addresses that have been attempted.
Each address is a string in the form of$IP:$PORT
. If the connection was successful,then the last address is the one that the socket is currently connected to.
socket.bufferSize
#
writable.writableLength
instead.This property shows the number of characters buffered for writing. The buffermay contain strings whose length after encoding is not yet known. So this numberis only an approximation of the number of bytes in the buffer.
net.Socket
has the property thatsocket.write()
always works. This is tohelp users get up and running quickly. The computer cannot always keep upwith the amount of data that is written to a socket. The network connectionsimply might be too slow. Node.js will internally queue up the data written to asocket and send it out over the wire when it is possible.
The consequence of this internal buffering is that memory may grow.Users who experience large or growingbufferSize
should attempt to"throttle" the data flows in their program withsocket.pause()
andsocket.resume()
.
socket.connect()
#
Initiate a connection on a given socket.
Possible signatures:
socket.connect(options[, connectListener])
socket.connect(path[, connectListener])
forIPC connections.socket.connect(port[, host][, connectListener])
for TCP connections.- Returns:<net.Socket> The socket itself.
This function is asynchronous. When the connection is established, the'connect'
event will be emitted. If there is a problem connecting,instead of a'connect'
event, an'error'
event will be emitted withthe error passed to the'error'
listener.The last parameterconnectListener
, if supplied, will be added as a listenerfor the'connect'
eventonce.
This function should only be used for reconnecting a socket after'close'
has been emitted or otherwise it may lead to undefinedbehavior.
socket.connect(options[, connectListener])
#
History
Version | Changes |
---|---|
v19.4.0 | The default value for autoSelectFamily option can be changed at runtime using |
v20.0.0, v18.18.0 | The default value for the autoSelectFamily option is now true. The |
v19.3.0, v18.13.0 | Added the |
v17.7.0, v16.15.0 | The |
v6.0.0 | The |
v5.11.0 | The |
v0.1.90 | Added in: v0.1.90 |
options
<Object>connectListener
<Function> Common parameter ofsocket.connect()
methods. Will be added as a listener for the'connect'
event once.- Returns:<net.Socket> The socket itself.
Initiate a connection on a given socket. Normally this method is not needed,the socket should be created and opened withnet.createConnection()
. Usethis only when implementing a custom Socket.
For TCP connections, availableoptions
are:
autoSelectFamily
<boolean>: If set totrue
, it enables a familyautodetection algorithm that loosely implements section 5 ofRFC 8305. Theall
option passed to lookup is set totrue
and the sockets attempts toconnect to all obtained IPv6 and IPv4 addresses, in sequence, until aconnection is established. The first returned AAAA address is tried first,then the first returned A address, then the second returned AAAA address andso on. Each connection attempt (but the last one) is given the amount of timespecified by theautoSelectFamilyAttemptTimeout
option before timing out andtrying the next address. Ignored if thefamily
option is not0
or iflocalAddress
is set. Connection errors are not emitted if at least oneconnection succeeds. If all connections attempts fails, a singleAggregateError
with all failed attempts is emitted.Default:net.getDefaultAutoSelectFamily()
.autoSelectFamilyAttemptTimeout
<number>: The amount of time in millisecondsto wait for a connection attempt to finish before trying the next address whenusing theautoSelectFamily
option. If set to a positive integer less than10
, then the value10
will be used instead.Default:net.getDefaultAutoSelectFamilyAttemptTimeout()
.family
<number>: Version of IP stack. Must be4
,6
, or0
. The value0
indicates that both IPv4 and IPv6 addresses are allowed.Default:0
.hints
<number> Optionaldns.lookup()
hints.host
<string> Host the socket should connect to.Default:'localhost'
.keepAlive
<boolean> If set totrue
, it enables keep-alive functionality onthe socket immediately after the connection is established, similarly on whatis done insocket.setKeepAlive()
.Default:false
.keepAliveInitialDelay
<number> If set to a positive number, it sets theinitial delay before the first keepalive probe is sent on an idle socket.Default:0
.localAddress
<string> Local address the socket should connect from.localPort
<number> Local port the socket should connect from.lookup
<Function> Custom lookup function.Default:dns.lookup()
.noDelay
<boolean> If set totrue
, it disables the use of Nagle's algorithmimmediately after the socket is established.Default:false
.port
<number> Required. Port the socket should connect to.blockList
<net.BlockList>blockList
can be used for disabling outboundaccess to specific IP addresses, IP ranges, or IP subnets.
ForIPC connections, availableoptions
are:
path
<string> Required. Path the client should connect to.SeeIdentifying paths for IPC connections. If provided, the TCP-specificoptions above are ignored.
socket.connect(path[, connectListener])
#
path
<string> Path the client should connect to. SeeIdentifying paths for IPC connections.connectListener
<Function> Common parameter ofsocket.connect()
methods. Will be added as a listener for the'connect'
event once.- Returns:<net.Socket> The socket itself.
Initiate anIPC connection on the given socket.
Alias tosocket.connect(options[, connectListener])
called with{ path: path }
asoptions
.
socket.connect(port[, host][, connectListener])
#
port
<number> Port the client should connect to.host
<string> Host the client should connect to.connectListener
<Function> Common parameter ofsocket.connect()
methods. Will be added as a listener for the'connect'
event once.- Returns:<net.Socket> The socket itself.
Initiate a TCP connection on the given socket.
Alias tosocket.connect(options[, connectListener])
called with{port: port, host: host}
asoptions
.
socket.connecting
#
Iftrue
,socket.connect(options[, connectListener])
wascalled and has not yet finished. It will staytrue
until the socket becomesconnected, then it is set tofalse
and the'connect'
event is emitted. Notethat thesocket.connect(options[, connectListener])
callback is a listener for the'connect'
event.
socket.destroy([error])
#
error
<Object>- Returns:<net.Socket>
Ensures that no more I/O activity happens on this socket.Destroys the stream and closes the connection.
Seewritable.destroy()
for further details.
socket.destroyed
#
- <boolean> Indicates if the connection is destroyed or not. Once aconnection is destroyed no further data can be transferred using it.
Seewritable.destroyed
for further details.
socket.destroySoon()
#
Destroys the socket after all data is written. If the'finish'
event wasalready emitted the socket is destroyed immediately. If the socket is stillwritable it implicitly callssocket.end()
.
socket.end([data[, encoding]][, callback])
#
data
<string> |<Buffer> |<Uint8Array>encoding
<string> Only used when data isstring
.Default:'utf8'
.callback
<Function> Optional callback for when the socket is finished.- Returns:<net.Socket> The socket itself.
Half-closes the socket. i.e., it sends a FIN packet. It is possible theserver will still send some data.
Seewritable.end()
for further details.
socket.localAddress
#
The string representation of the local IP address the remote client isconnecting on. For example, in a server listening on'0.0.0.0'
, if a clientconnects on'192.168.1.1'
, the value ofsocket.localAddress
would be'192.168.1.1'
.
socket.localFamily
#
The string representation of the local IP family.'IPv4'
or'IPv6'
.
socket.pause()
#
- Returns:<net.Socket> The socket itself.
Pauses the reading of data. That is,'data'
events will not be emitted.Useful to throttle back an upload.
socket.pending
#
This istrue
if the socket is not connected yet, either because.connect()
has not yet been called or because it is still in the process of connecting(seesocket.connecting
).
socket.ref()
#
- Returns:<net.Socket> The socket itself.
Opposite ofunref()
, callingref()
on a previouslyunref
ed socket willnot let the program exit if it's the only socket left (the default behavior).If the socket isref
ed callingref
again will have no effect.
socket.remoteAddress
#
The string representation of the remote IP address. For example,'74.125.127.100'
or'2001:4860:a005::68'
. Value may beundefined
ifthe socket is destroyed (for example, if the client disconnected).
socket.remoteFamily
#
The string representation of the remote IP family.'IPv4'
or'IPv6'
. Value may beundefined
ifthe socket is destroyed (for example, if the client disconnected).
socket.remotePort
#
The numeric representation of the remote port. For example,80
or21
. Value may beundefined
ifthe socket is destroyed (for example, if the client disconnected).
socket.resetAndDestroy()
#
- Returns:<net.Socket>
Close the TCP connection by sending an RST packet and destroy the stream.If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.Otherwise, it will callsocket.destroy
with anERR_SOCKET_CLOSED
Error.If this is not a TCP socket (for example, a pipe), calling this method will immediately throw anERR_INVALID_HANDLE_TYPE
Error.
socket.resume()
#
- Returns:<net.Socket> The socket itself.
Resumes reading after a call tosocket.pause()
.
socket.setEncoding([encoding])
#
encoding
<string>- Returns:<net.Socket> The socket itself.
Set the encoding for the socket as aReadable Stream. Seereadable.setEncoding()
for more information.
socket.setKeepAlive([enable][, initialDelay])
#
History
Version | Changes |
---|---|
v13.12.0, v12.17.0 | New defaults for |
v0.1.92 | Added in: v0.1.92 |
enable
<boolean>Default:false
initialDelay
<number>Default:0
- Returns:<net.Socket> The socket itself.
Enable/disable keep-alive functionality, and optionally set the initialdelay before the first keepalive probe is sent on an idle socket.
SetinitialDelay
(in milliseconds) to set the delay between the lastdata packet received and the first keepalive probe. Setting0
forinitialDelay
will leave the value unchanged from the default(or previous) setting.
Enabling the keep-alive functionality will set the following socket options:
SO_KEEPALIVE=1
TCP_KEEPIDLE=initialDelay
TCP_KEEPCNT=10
TCP_KEEPINTVL=1
socket.setNoDelay([noDelay])
#
noDelay
<boolean>Default:true
- Returns:<net.Socket> The socket itself.
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 attemptsto optimize throughput at the expense of latency.
Passingtrue
fornoDelay
or not passing an argument will disable Nagle'salgorithm for the socket. Passingfalse
fornoDelay
will enable Nagle'salgorithm.
socket.setTimeout(timeout[, callback])
#
History
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v0.1.90 | Added in: v0.1.90 |
timeout
<number>callback
<Function>- Returns:<net.Socket> The socket itself.
Sets the socket to timeout aftertimeout
milliseconds of inactivity onthe socket. By defaultnet.Socket
do not have a timeout.
When an idle timeout is triggered the socket will receive a'timeout'
event but the connection will not be severed. The user must manually callsocket.end()
orsocket.destroy()
to end the connection.
socket.setTimeout(3000);socket.on('timeout',() => {console.log('socket timeout'); socket.end();});
Iftimeout
is 0, then the existing idle timeout is disabled.
The optionalcallback
parameter will be added as a one-time listener for the'timeout'
event.
socket.timeout
#
The socket timeout in milliseconds as set bysocket.setTimeout()
.It isundefined
if a timeout has not been set.
socket.unref()
#
- Returns:<net.Socket> The socket itself.
Callingunref()
on a socket will allow the program to exit if this is the onlyactive socket in the event system. If the socket is alreadyunref
ed callingunref()
again will have no effect.
socket.write(data[, encoding][, callback])
#
data
<string> |<Buffer> |<Uint8Array>encoding
<string> Only used when data isstring
.Default:utf8
.callback
<Function>- Returns:<boolean>
Sends data on the socket. The second parameter specifies the encoding in thecase of a string. It defaults to UTF8 encoding.
Returnstrue
if the entire data was flushed successfully to the kernelbuffer. Returnsfalse
if all or part of the data was queued in user memory.'drain'
will be emitted when the buffer is again free.
The optionalcallback
parameter will be executed when the data is finallywritten out, which may not be immediately.
SeeWritable
streamwrite()
method for moreinformation.
socket.readyState
#
This property represents the state of the connection as a string.
- If the stream is connecting
socket.readyState
isopening
. - If the stream is readable and writable, it is
open
. - If the stream is readable and not writable, it is
readOnly
. - If the stream is not readable and writable, it is
writeOnly
.
net.connect()
#
Aliases tonet.createConnection()
.
Possible signatures:
net.connect(options[, connectListener])
net.connect(path[, connectListener])
forIPCconnections.net.connect(port[, host][, connectListener])
for TCP connections.
net.connect(options[, connectListener])
#
options
<Object>connectListener
<Function>- Returns:<net.Socket>
net.connect(path[, connectListener])
#
path
<string>connectListener
<Function>- Returns:<net.Socket>
net.connect(port[, host][, connectListener])
#
port
<number>host
<string>connectListener
<Function>- Returns:<net.Socket>
Alias tonet.createConnection(port[, host][, connectListener])
.
net.createConnection()
#
A factory function, which creates a newnet.Socket
,immediately initiates connection withsocket.connect()
,then returns thenet.Socket
that starts the connection.
When the connection is established, a'connect'
event will be emittedon the returned socket. The last parameterconnectListener
, if supplied,will be added as a listener for the'connect'
eventonce.
Possible signatures:
net.createConnection(options[, connectListener])
net.createConnection(path[, connectListener])
forIPC connections.net.createConnection(port[, host][, connectListener])
for TCP connections.
Thenet.connect()
function is an alias to this function.
net.createConnection(options[, connectListener])
#
options
<Object> Required. Will be passed to both thenew net.Socket([options])
call and thesocket.connect(options[, connectListener])
method.connectListener
<Function> Common parameter of thenet.createConnection()
functions. If supplied, will be added asa listener for the'connect'
event on the returned socket once.- Returns:<net.Socket> The newly created socket used to start the connection.
For available options, seenew net.Socket([options])
andsocket.connect(options[, connectListener])
.
Additional options:
timeout
<number> If set, will be used to callsocket.setTimeout(timeout)
after the socket is created, but beforeit starts the connection.
Following is an example of a client of the echo server describedin thenet.createServer()
section:
import netfrom'node:net';const client = net.createConnection({port:8124 },() => {// 'connect' listener.console.log('connected to server!'); client.write('world!\r\n');});client.on('data',(data) => {console.log(data.toString()); client.end();});client.on('end',() => {console.log('disconnected from server');});
const net =require('node:net');const client = net.createConnection({port:8124 },() => {// 'connect' listener.console.log('connected to server!'); client.write('world!\r\n');});client.on('data',(data) => {console.log(data.toString()); client.end();});client.on('end',() => {console.log('disconnected from server');});
To connect on the socket/tmp/echo.sock
:
const client = net.createConnection({path:'/tmp/echo.sock' });
Following is an example of a client using theport
andonread
option. In this case, theonread
option will be only used to callnew net.Socket([options])
and theport
option will be used tocallsocket.connect(options[, connectListener])
.
import netfrom'node:net';import {Buffer }from'node:buffer';net.createConnection({port:8124,onread: {// Reuses a 4KiB Buffer for every read from the socket.buffer:Buffer.alloc(4 *1024),callback:function(nread, buf) {// Received data is available in `buf` from 0 to `nread`.console.log(buf.toString('utf8',0, nread)); }, },});
const net =require('node:net');net.createConnection({port:8124,onread: {// Reuses a 4KiB Buffer for every read from the socket.buffer:Buffer.alloc(4 *1024),callback:function(nread, buf) {// Received data is available in `buf` from 0 to `nread`.console.log(buf.toString('utf8',0, nread)); }, },});
net.createConnection(path[, connectListener])
#
path
<string> Path the socket should connect to. Will be passed tosocket.connect(path[, connectListener])
.SeeIdentifying paths for IPC connections.connectListener
<Function> Common parameter of thenet.createConnection()
functions, an "once" listener for the'connect'
event on the initiating socket. Will be passed tosocket.connect(path[, connectListener])
.- Returns:<net.Socket> The newly created socket used to start the connection.
Initiates anIPC connection.
This function creates a newnet.Socket
with all options set to default,immediately initiates connection withsocket.connect(path[, connectListener])
,then returns thenet.Socket
that starts the connection.
net.createConnection(port[, host][, connectListener])
#
port
<number> Port the socket should connect to. Will be passed tosocket.connect(port[, host][, connectListener])
.host
<string> Host the socket should connect to. Will be passed tosocket.connect(port[, host][, connectListener])
.Default:'localhost'
.connectListener
<Function> Common parameter of thenet.createConnection()
functions, an "once" listener for the'connect'
event on the initiating socket. Will be passed tosocket.connect(port[, host][, connectListener])
.- Returns:<net.Socket> The newly created socket used to start the connection.
Initiates a TCP connection.
This function creates a newnet.Socket
with all options set to default,immediately initiates connection withsocket.connect(port[, host][, connectListener])
,then returns thenet.Socket
that starts the connection.
net.createServer([options][, connectionListener])
#
History
Version | Changes |
---|---|
v20.1.0, v18.17.0 | The |
v17.7.0, v16.15.0 | The |
v0.5.0 | Added in: v0.5.0 |
options
<Object>allowHalfOpen
<boolean> If set tofalse
, then the socket willautomatically end the writable side when the readable side ends.Default:false
.highWaterMark
<number> Optionally overrides allnet.Socket
s'readableHighWaterMark
andwritableHighWaterMark
.Default: Seestream.getDefaultHighWaterMark()
.keepAlive
<boolean> If set totrue
, it enables keep-alive functionalityon the socket immediately after a new incoming connection is received,similarly on what is done insocket.setKeepAlive()
.Default:false
.keepAliveInitialDelay
<number> If set to a positive number, it sets theinitial delay before the first keepalive probe is sent on an idle socket.Default:0
.noDelay
<boolean> If set totrue
, it disables the use of Nagle'salgorithm immediately after a new incoming connection is received.Default:false
.pauseOnConnect
<boolean> Indicates whether the socket should bepaused on incoming connections.Default:false
.blockList
<net.BlockList>blockList
can be used for disabling inboundaccess to specific IP addresses, IP ranges, or IP subnets. This does notwork if the server is behind a reverse proxy, NAT, etc. because the addresschecked against the block list is the address of the proxy, or the onespecified by the NAT.
connectionListener
<Function> Automatically set as a listener for the'connection'
event.Returns:<net.Server>
Creates a new TCP orIPC server.
IfallowHalfOpen
is set totrue
, when the other end of the socketsignals the end of transmission, the server will only send back the end oftransmission whensocket.end()
is explicitly called. For example, in thecontext of TCP, when a FIN packed is received, a FIN packed is sentback only whensocket.end()
is explicitly called. Until then theconnection is half-closed (non-readable but still writable). See'end'
event andRFC 1122 (section 4.2.2.13) for more information.
IfpauseOnConnect
is set totrue
, then the socket associated with eachincoming connection will be paused, and no data will be read from its handle.This allows connections to be passed between processes without any data beingread by the original process. To begin reading data from a paused socket, callsocket.resume()
.
The server can be a TCP server or anIPC server, depending on what itlisten()
to.
Here is an example of a TCP echo server which listens for connectionson port 8124:
import netfrom'node:net';const server = net.createServer((c) => {// 'connection' listener.console.log('client connected'); c.on('end',() => {console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c);});server.on('error',(err) => {throw err;});server.listen(8124,() => {console.log('server bound');});
const net =require('node:net');const server = net.createServer((c) => {// 'connection' listener.console.log('client connected'); c.on('end',() => {console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c);});server.on('error',(err) => {throw err;});server.listen(8124,() => {console.log('server bound');});
Test this by usingtelnet
:
telnet localhost 8124
To listen on the socket/tmp/echo.sock
:
server.listen('/tmp/echo.sock',() => {console.log('server bound');});
Usenc
to connect to a Unix domain socket server:
nc -U /tmp/echo.sock
net.getDefaultAutoSelectFamily()
#
Gets the current default value of theautoSelectFamily
option ofsocket.connect(options)
.The initial default value istrue
, unless the command line option--no-network-family-autoselection
is provided.
- Returns:<boolean> The current default value of the
autoSelectFamily
option.
net.setDefaultAutoSelectFamily(value)
#
Sets the default value of theautoSelectFamily
option ofsocket.connect(options)
.
value
<boolean> The new default value.The initial default value istrue
, unless the command line option--no-network-family-autoselection
is provided.
net.getDefaultAutoSelectFamilyAttemptTimeout()
#
Gets the current default value of theautoSelectFamilyAttemptTimeout
option ofsocket.connect(options)
.The initial default value is250
or the value specified via the command lineoption--network-family-autoselection-attempt-timeout
.
- Returns:<number> The current default value of the
autoSelectFamilyAttemptTimeout
option.
net.setDefaultAutoSelectFamilyAttemptTimeout(value)
#
Sets the default value of theautoSelectFamilyAttemptTimeout
option ofsocket.connect(options)
.
value
<number> The new default value, which must be a positive number. If the number is less than10
,the value10
is used instead. The initial default value is250
or the value specified via the command lineoption--network-family-autoselection-attempt-timeout
.
net.isIP(input)
#
Returns6
ifinput
is an IPv6 address. Returns4
ifinput
is an IPv4address indot-decimal notation with no leading zeroes. Otherwise, returns0
.
net.isIP('::1');// returns 6net.isIP('127.0.0.1');// returns 4net.isIP('127.000.000.001');// returns 0net.isIP('127.0.0.1/24');// returns 0net.isIP('fhqwhgads');// returns 0
net.isIPv4(input)
#
Returnstrue
ifinput
is an IPv4 address indot-decimal notation with noleading zeroes. Otherwise, returnsfalse
.
net.isIPv4('127.0.0.1');// returns truenet.isIPv4('127.000.000.001');// returns falsenet.isIPv4('127.0.0.1/24');// returns falsenet.isIPv4('fhqwhgads');// returns false
net.isIPv6(input)
#
Returnstrue
ifinput
is an IPv6 address. Otherwise, returnsfalse
.
net.isIPv6('::1');// returns truenet.isIPv6('fhqwhgads');// returns false