Net#

Stability: 2 - Stable

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
VersionChanges
v20.8.0

Support binding to abstract Unix domain socket path like\0abstract. We can bind '\0' for Node.js< v20.4.0.

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#

Added in: v15.0.0, v14.18.0

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])#

Added in: v15.0.0, v14.18.0

Adds a rule to block the given IP address.

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

Added in: v15.0.0, v14.18.0

Adds a rule to block a range of IP addresses fromstart (inclusive) toend (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, 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])#

Added in: v15.0.0, v14.18.0

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

blockList.rules#

Added in: v15.0.0, v14.18.0

The list of rules added to the blocklist.

BlockList.isBlockList(value)#

Added in: v23.4.0, v22.13.0
  • value<any> Any JS value
  • Returnstrue if thevalue is anet.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' iffamily is'ipv4';'::' iffamily is'ipv6'.
    • family<string> One of either'ipv4' or'ipv6'.Default:'ipv4'.
    • flowlabel<number> An IPv6 flow-label used only iffamily is'ipv6'.
    • port<number> An IP port.

socketaddress.address#

Added in: v15.14.0, v14.18.0

socketaddress.family#

Added in: v15.14.0, v14.18.0

socketaddress.flowlabel#

Added in: v15.14.0, v14.18.0

socketaddress.port#

Added in: v15.14.0, v14.18.0

SocketAddress.parse(input)#

Added in: v23.4.0, v22.13.0
  • 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 aSocketAddress if parsing was successful.Otherwise returnsundefined.

Class:net.Server#

Added in: v0.1.90

This class is used to create a TCP orIPC server.

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

net.Server is anEventEmitter with the following events:

Event:'close'#

Added in: v0.5.0

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

Event:'connection'#

Added in: v0.1.90

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

Event:'error'#

Added in: v0.1.90

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'#

Added in: v0.1.90

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

Event:'drop'#

Added in: v18.6.0, v16.17.0

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
VersionChanges
v18.4.0

Thefamily property now returns a string instead of a number.

v18.0.0

Thefamily property now returns a number instead of a string.

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])#

Added in: v0.1.90

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
VersionChanges
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)#

Added in: v0.9.7

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:

This function is asynchronous. When the server starts listening, the'listening' event will be emitted. The last parametercallbackwill 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 andsomaxconnon 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])#
Added in: v0.5.10

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
VersionChanges
v23.1.0, v22.12.0

ThereusePort option is supported.

v15.6.0

AbortSignal support was added.

v11.4.0

Theipv6Only option is supported.

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])#
Added in: v0.1.90

Start anIPC server listening for connections on the givenpath.

server.listen([port[, host[, backlog]]][, callback])#
Added in: v0.1.90

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().portafter 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#

Added in: v5.7.0
  • <boolean> Indicates whether or not the server is listening for connections.

server.maxConnections#

History
VersionChanges
v21.0.0

SettingmaxConnections to0 drops all the incoming connections. Previously, it was interpreted asInfinity.

v0.2.0

Added in: v0.2.0

When the number of connections reaches theserver.maxConnections threshold:

  1. If the process is not running in cluster mode, Node.js will close the connection.

  2. 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#

Added in: v23.1.0, v22.12.0

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()#

Added in: v0.9.1

Opposite ofunref(), callingref() on a previouslyunrefed server willnot let the program exit if it's the only server left (the default behavior).If the server isrefed callingref() again will have no effect.

server.unref()#

Added in: v0.9.1

Callingunref() on a server will allow the program to exit if this is the onlyactive server in the event system. If the server is alreadyunrefed callingunref() again will have no effect.

Class:net.Socket#

Added in: v0.3.4

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
VersionChanges
v15.14.0

AbortSignal support was added.

v12.10.0

Addedonread option.

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 singlebufferand 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'#

Added in: v0.1.90
  • 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'#

Added in: v0.1.90

Emitted when a socket connection is successfully established.Seenet.createConnection().

Event:'connectionAttempt'#

Added in: v21.6.0, v20.12.0
  • 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'#

Added in: v21.6.0, v20.12.0
  • 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'#

Added in: v21.6.0, v20.12.0
  • 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'#

Added in: v0.1.90

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 aSocketemits a'data' event.

Event:'drain'#

Added in: v0.1.90

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

See also: the return values ofsocket.write().

Event:'end'#

Added in: v0.1.90

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'#

Added in: v0.1.90

Emitted when an error occurs. The'close' event will be called directlyfollowing this event.

Event:'lookup'#

History
VersionChanges
v5.10.0

Thehost parameter is supported now.

v0.11.3

Added in: v0.11.3

Emitted after resolving the host name but before connecting.Not applicable to Unix sockets.

Event:'ready'#

Added in: v9.11.0

Emitted when a socket is ready to be used.

Triggered immediately after'connect'.

Event:'timeout'#

Added in: v0.1.90

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
VersionChanges
v18.4.0

Thefamily property now returns a string instead of a number.

v18.0.0

Thefamily property now returns a number instead of a string.

v0.1.90

Added in: v0.1.90

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#

Added in: v19.4.0, v18.18.0

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#

Added in: v0.3.8Deprecated since: v14.6.0

Stability: 0 - Deprecated: Usewritable.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.bytesRead#

Added in: v0.5.3

The amount of received bytes.

socket.bytesWritten#

Added in: v0.5.3

The amount of bytes sent.

socket.connect()#

Initiate a connection on a given socket.

Possible signatures:

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
VersionChanges
v19.4.0

The default value for autoSelectFamily option can be changed at runtime usingsetDefaultAutoSelectFamily or via the command line option--enable-network-family-autoselection.

v20.0.0, v18.18.0

The default value for the autoSelectFamily option is now true. The--enable-network-family-autoselection CLI flag has been renamed to--network-family-autoselection. The old name is now an alias but it is discouraged.

v19.3.0, v18.13.0

Added theautoSelectFamily option.

v17.7.0, v16.15.0

ThenoDelay,keepAlive, andkeepAliveInitialDelay options are supported now.

v6.0.0

Thehints option defaults to0 in all cases now. Previously, in the absence of thefamily option it would default todns.ADDRCONFIG | dns.V4MAPPED.

v5.11.0

Thehints option is supported now.

v0.1.90

Added in: v0.1.90

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:

socket.connect(path[, connectListener])#

Initiate anIPC connection on the given socket.

Alias tosocket.connect(options[, connectListener])called with{ path: path } asoptions.

socket.connect(port[, host][, connectListener])#
Added in: v0.1.90

Initiate a TCP connection on the given socket.

Alias tosocket.connect(options[, connectListener])called with{port: port, host: host} asoptions.

socket.connecting#

Added in: v6.1.0

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])#

Added in: v0.1.90

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()#

Added in: v0.3.4

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])#

Added in: v0.1.90

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#

Added in: v0.9.6

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.localPort#

Added in: v0.9.6

The numeric representation of the local port. For example,80 or21.

socket.localFamily#

Added in: v18.8.0, v16.18.0

The string representation of the local IP family.'IPv4' or'IPv6'.

socket.pause()#

Pauses the reading of data. That is,'data' events will not be emitted.Useful to throttle back an upload.

socket.pending#

Added in: v11.2.0, v10.16.0

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()#

Added in: v0.9.1

Opposite ofunref(), callingref() on a previouslyunrefed socket willnot let the program exit if it's the only socket left (the default behavior).If the socket isrefed callingref again will have no effect.

socket.remoteAddress#

Added in: v0.5.10

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#

Added in: v0.11.14

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#

Added in: v0.5.10

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()#

Added in: v18.3.0, v16.17.0

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()#

Resumes reading after a call tosocket.pause().

socket.setEncoding([encoding])#

Added in: v0.1.90

Set the encoding for the socket as aReadable Stream. Seereadable.setEncoding() for more information.

socket.setKeepAlive([enable][, initialDelay])#

History
VersionChanges
v13.12.0, v12.17.0

New defaults forTCP_KEEPCNT andTCP_KEEPINTVL socket options were added.

v0.1.92

Added in: v0.1.92

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])#

Added in: v0.1.90

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
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v0.1.90

Added in: v0.1.90

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#

Added in: v10.7.0

The socket timeout in milliseconds as set bysocket.setTimeout().It isundefined if a timeout has not been set.

socket.unref()#

Added in: v0.9.1

Callingunref() on a socket will allow the program to exit if this is the onlyactive socket in the event system. If the socket is alreadyunrefed callingunref() again will have no effect.

socket.write(data[, encoding][, callback])#

Added in: v0.1.90

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#

Added in: v0.5.0

This property represents the state of the connection as a string.

  • If the stream is connectingsocket.readyState isopening.
  • If the stream is readable and writable, it isopen.
  • If the stream is readable and not writable, it isreadOnly.
  • If the stream is not readable and writable, it iswriteOnly.

net.connect()#

Aliases tonet.createConnection().

Possible signatures:

net.connect(options[, connectListener])#

Added in: v0.7.0

Alias tonet.createConnection(options[, connectListener]).

net.connect(path[, connectListener])#

Added in: v0.1.90

Alias tonet.createConnection(path[, connectListener]).

net.connect(port[, host][, connectListener])#

Added in: v0.1.90

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:

Thenet.connect() function is an alias to this function.

net.createConnection(options[, connectListener])#

Added in: v0.1.90

For available options, seenew net.Socket([options])andsocket.connect(options[, connectListener]).

Additional options:

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 andonreadoption. 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])#

Added in: v0.1.90

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])#

Added in: v0.1.90

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
VersionChanges
v20.1.0, v18.17.0

ThehighWaterMark option is supported now.

v17.7.0, v16.15.0

ThenoDelay,keepAlive, andkeepAliveInitialDelay options are supported now.

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.Sockets'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()#

Added in: v19.4.0

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 theautoSelectFamily option.

net.setDefaultAutoSelectFamily(value)#

Added in: v19.4.0

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()#

Added in: v19.8.0, v18.18.0

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 theautoSelectFamilyAttemptTimeout option.

net.setDefaultAutoSelectFamilyAttemptTimeout(value)#

Added in: v19.8.0, v18.18.0

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)#

Added in: v0.3.0

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)#

Added in: v0.3.0

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)#

Added in: v0.3.0

Returnstrue ifinput is an IPv6 address. Otherwise, returnsfalse.

net.isIPv6('::1');// returns truenet.isIPv6('fhqwhgads');// returns false