1# Net 2 3<!--introduced_in=v0.10.0--> 4 5<!--lint disable maximum-line-length--> 6 7> Stability: 2 - Stable 8 9<!-- source_link=lib/net.js --> 10 11The `node:net` module provides an asynchronous network API for creating stream-based 12TCP or [IPC][] servers ([`net.createServer()`][]) and clients 13([`net.createConnection()`][]). 14 15It can be accessed using: 16 17```js 18const net = require('node:net'); 19``` 20 21## IPC support 22 23The `node:net` module supports IPC with named pipes on Windows, and Unix domain 24sockets on other operating systems. 25 26### Identifying paths for IPC connections 27 28[`net.connect()`][], [`net.createConnection()`][], [`server.listen()`][], and 29[`socket.connect()`][] take a `path` parameter to identify IPC endpoints. 30 31On Unix, the local domain is also known as the Unix domain. The path is a 32file system pathname. It gets truncated to an OS-dependent length of 33`sizeof(sockaddr_un.sun_path) - 1`. Typical values are 107 bytes on Linux and 34103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, 35it will unlink the Unix domain socket as well. For example, 36[`net.createServer()`][] may create a Unix domain socket and 37[`server.close()`][] will unlink it. But if a user creates the Unix domain 38socket outside of these abstractions, the user will need to remove it. The same 39applies when a Node.js API creates a Unix domain socket but the program then 40crashes. In short, a Unix domain socket will be visible in the file system and 41will persist until unlinked. 42 43On Windows, the local domain is implemented using a named pipe. The path _must_ 44refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted, 45but the latter may do some processing of pipe names, such as resolving `..` 46sequences. Despite how it might look, the pipe namespace is flat. Pipes will 47_not persist_. They are removed when the last reference to them is closed. 48Unlike Unix domain sockets, Windows will close and remove the pipe when the 49owning process exits. 50 51JavaScript string escaping requires paths to be specified with extra backslash 52escaping such as: 53 54```js 55net.createServer().listen( 56 path.join('\\\\?\\pipe', process.cwd(), 'myctl')); 57``` 58 59## Class: `net.BlockList` 60 61<!-- YAML 62added: 63 - v15.0.0 64 - v14.18.0 65--> 66 67The `BlockList` object can be used with some network APIs to specify rules for 68disabling inbound or outbound access to specific IP addresses, IP ranges, or 69IP subnets. 70 71### `blockList.addAddress(address[, type])` 72 73<!-- YAML 74added: 75 - v15.0.0 76 - v14.18.0 77--> 78 79* `address` {string|net.SocketAddress} An IPv4 or IPv6 address. 80* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. 81 82Adds a rule to block the given IP address. 83 84### `blockList.addRange(start, end[, type])` 85 86<!-- YAML 87added: 88 - v15.0.0 89 - v14.18.0 90--> 91 92* `start` {string|net.SocketAddress} The starting IPv4 or IPv6 address in the 93 range. 94* `end` {string|net.SocketAddress} The ending IPv4 or IPv6 address in the range. 95* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. 96 97Adds a rule to block a range of IP addresses from `start` (inclusive) to 98`end` (inclusive). 99 100### `blockList.addSubnet(net, prefix[, type])` 101 102<!-- YAML 103added: 104 - v15.0.0 105 - v14.18.0 106--> 107 108* `net` {string|net.SocketAddress} The network IPv4 or IPv6 address. 109* `prefix` {number} The number of CIDR prefix bits. For IPv4, this 110 must be a value between `0` and `32`. For IPv6, this must be between 111 `0` and `128`. 112* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. 113 114Adds a rule to block a range of IP addresses specified as a subnet mask. 115 116### `blockList.check(address[, type])` 117 118<!-- YAML 119added: 120 - v15.0.0 121 - v14.18.0 122--> 123 124* `address` {string|net.SocketAddress} The IP address to check 125* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. 126* Returns: {boolean} 127 128Returns `true` if the given IP address matches any of the rules added to the 129`BlockList`. 130 131```js 132const blockList = new net.BlockList(); 133blockList.addAddress('123.123.123.123'); 134blockList.addRange('10.0.0.1', '10.0.0.10'); 135blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); 136 137console.log(blockList.check('123.123.123.123')); // Prints: true 138console.log(blockList.check('10.0.0.3')); // Prints: true 139console.log(blockList.check('222.111.111.222')); // Prints: false 140 141// IPv6 notation for IPv4 addresses works: 142console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true 143console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true 144``` 145 146### `blockList.rules` 147 148<!-- YAML 149added: 150 - v15.0.0 151 - v14.18.0 152--> 153 154* Type: {string\[]} 155 156The list of rules added to the blocklist. 157 158## Class: `net.SocketAddress` 159 160<!-- YAML 161added: 162 - v15.14.0 163 - v14.18.0 164--> 165 166### `new net.SocketAddress([options])` 167 168<!-- YAML 169added: 170 - v15.14.0 171 - v14.18.0 172--> 173 174* `options` {Object} 175 * `address` {string} The network address as either an IPv4 or IPv6 string. 176 **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is 177 `'ipv6'`. 178 * `family` {string} One of either `'ipv4'` or `'ipv6'`. 179 **Default**: `'ipv4'`. 180 * `flowlabel` {number} An IPv6 flow-label used only if `family` is `'ipv6'`. 181 * `port` {number} An IP port. 182 183### `socketaddress.address` 184 185<!-- YAML 186added: 187 - v15.14.0 188 - v14.18.0 189--> 190 191* Type {string} 192 193### `socketaddress.family` 194 195<!-- YAML 196added: 197 - v15.14.0 198 - v14.18.0 199--> 200 201* Type {string} Either `'ipv4'` or `'ipv6'`. 202 203### `socketaddress.flowlabel` 204 205<!-- YAML 206added: 207 - v15.14.0 208 - v14.18.0 209--> 210 211* Type {number} 212 213### `socketaddress.port` 214 215<!-- YAML 216added: 217 - v15.14.0 218 - v14.18.0 219--> 220 221* Type {number} 222 223## Class: `net.Server` 224 225<!-- YAML 226added: v0.1.90 227--> 228 229* Extends: {EventEmitter} 230 231This class is used to create a TCP or [IPC][] server. 232 233### `new net.Server([options][, connectionListener])` 234 235* `options` {Object} See 236 [`net.createServer([options][, connectionListener])`][`net.createServer()`]. 237* `connectionListener` {Function} Automatically set as a listener for the 238 [`'connection'`][] event. 239* Returns: {net.Server} 240 241`net.Server` is an [`EventEmitter`][] with the following events: 242 243### Event: `'close'` 244 245<!-- YAML 246added: v0.5.0 247--> 248 249Emitted when the server closes. If connections exist, this 250event is not emitted until all connections are ended. 251 252### Event: `'connection'` 253 254<!-- YAML 255added: v0.1.90 256--> 257 258* {net.Socket} The connection object 259 260Emitted when a new connection is made. `socket` is an instance of 261`net.Socket`. 262 263### Event: `'error'` 264 265<!-- YAML 266added: v0.1.90 267--> 268 269* {Error} 270 271Emitted when an error occurs. Unlike [`net.Socket`][], the [`'close'`][] 272event will **not** be emitted directly following this event unless 273[`server.close()`][] is manually called. See the example in discussion of 274[`server.listen()`][]. 275 276### Event: `'listening'` 277 278<!-- YAML 279added: v0.1.90 280--> 281 282Emitted when the server has been bound after calling [`server.listen()`][]. 283 284### Event: `'drop'` 285 286<!-- YAML 287added: v18.6.0 288--> 289 290When the number of connections reaches the threshold of `server.maxConnections`, 291the server will drop new connections and emit `'drop'` event instead. If it is a 292TCP server, the argument is as follows, otherwise the argument is `undefined`. 293 294* `data` {Object} The argument passed to event listener. 295 * `localAddress` {string} Local address. 296 * `localPort` {number} Local port. 297 * `localFamily` {string} Local family. 298 * `remoteAddress` {string} Remote address. 299 * `remotePort` {number} Remote port. 300 * `remoteFamily` {string} Remote IP family. `'IPv4'` or `'IPv6'`. 301 302### `server.address()` 303 304<!-- YAML 305added: v0.1.90 306changes: 307 - version: v18.4.0 308 pr-url: https://github.com/nodejs/node/pull/43054 309 description: The `family` property now returns a string instead of a number. 310 - version: v18.0.0 311 pr-url: https://github.com/nodejs/node/pull/41431 312 description: The `family` property now returns a number instead of a string. 313--> 314 315* Returns: {Object|string|null} 316 317Returns the bound `address`, the address `family` name, and `port` of the server 318as reported by the operating system if listening on an IP socket 319(useful to find which port was assigned when getting an OS-assigned address): 320`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. 321 322For a server listening on a pipe or Unix domain socket, the name is returned 323as a string. 324 325```js 326const server = net.createServer((socket) => { 327 socket.end('goodbye\n'); 328}).on('error', (err) => { 329 // Handle errors here. 330 throw err; 331}); 332 333// Grab an arbitrary unused port. 334server.listen(() => { 335 console.log('opened server on', server.address()); 336}); 337``` 338 339`server.address()` returns `null` before the `'listening'` event has been 340emitted or after calling `server.close()`. 341 342### `server.close([callback])` 343 344<!-- YAML 345added: v0.1.90 346--> 347 348* `callback` {Function} Called when the server is closed. 349* Returns: {net.Server} 350 351Stops the server from accepting new connections and keeps existing 352connections. This function is asynchronous, the server is finally closed 353when all connections are ended and the server emits a [`'close'`][] event. 354The optional `callback` will be called once the `'close'` event occurs. Unlike 355that event, it will be called with an `Error` as its only argument if the server 356was not open when it was closed. 357 358### `server[Symbol.asyncDispose]()` 359 360<!-- YAML 361added: v18.18.0 362--> 363 364> Stability: 1 - Experimental 365 366Calls [`server.close()`][] and returns a promise that fulfills when the 367server has closed. 368 369### `server.getConnections(callback)` 370 371<!-- YAML 372added: v0.9.7 373--> 374 375* `callback` {Function} 376* Returns: {net.Server} 377 378Asynchronously get the number of concurrent connections on the server. Works 379when sockets were sent to forks. 380 381Callback should take two arguments `err` and `count`. 382 383### `server.listen()` 384 385Start a server listening for connections. A `net.Server` can be a TCP or 386an [IPC][] server depending on what it listens to. 387 388Possible signatures: 389 390* [`server.listen(handle[, backlog][, callback])`][`server.listen(handle)`] 391* [`server.listen(options[, callback])`][`server.listen(options)`] 392* [`server.listen(path[, backlog][, callback])`][`server.listen(path)`] 393 for [IPC][] servers 394* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`] 395 for TCP servers 396 397This function is asynchronous. When the server starts listening, the 398[`'listening'`][] event will be emitted. The last parameter `callback` 399will be added as a listener for the [`'listening'`][] event. 400 401All `listen()` methods can take a `backlog` parameter to specify the maximum 402length of the queue of pending connections. The actual length will be determined 403by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` 404on Linux. The default value of this parameter is 511 (not 512). 405 406All [`net.Socket`][] are set to `SO_REUSEADDR` (see [`socket(7)`][] for 407details). 408 409The `server.listen()` method can be called again if and only if there was an 410error during the first `server.listen()` call or `server.close()` has been 411called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. 412 413One of the most common errors raised when listening is `EADDRINUSE`. 414This happens when another server is already listening on the requested 415`port`/`path`/`handle`. One way to handle this would be to retry 416after a certain amount of time: 417 418```js 419server.on('error', (e) => { 420 if (e.code === 'EADDRINUSE') { 421 console.error('Address in use, retrying...'); 422 setTimeout(() => { 423 server.close(); 424 server.listen(PORT, HOST); 425 }, 1000); 426 } 427}); 428``` 429 430#### `server.listen(handle[, backlog][, callback])` 431 432<!-- YAML 433added: v0.5.10 434--> 435 436* `handle` {Object} 437* `backlog` {number} Common parameter of [`server.listen()`][] functions 438* `callback` {Function} 439* Returns: {net.Server} 440 441Start a server listening for connections on a given `handle` that has 442already been bound to a port, a Unix domain socket, or a Windows named pipe. 443 444The `handle` object can be either a server, a socket (anything with an 445underlying `_handle` member), or an object with an `fd` member that is a 446valid file descriptor. 447 448Listening on a file descriptor is not supported on Windows. 449 450#### `server.listen(options[, callback])` 451 452<!-- YAML 453added: v0.11.14 454changes: 455 - version: v15.6.0 456 pr-url: https://github.com/nodejs/node/pull/36623 457 description: AbortSignal support was added. 458 - version: v11.4.0 459 pr-url: https://github.com/nodejs/node/pull/23798 460 description: The `ipv6Only` option is supported. 461--> 462 463* `options` {Object} Required. Supports the following properties: 464 * `port` {number} 465 * `host` {string} 466 * `path` {string} Will be ignored if `port` is specified. See 467 [Identifying paths for IPC connections][]. 468 * `backlog` {number} Common parameter of [`server.listen()`][] 469 functions. 470 * `exclusive` {boolean} **Default:** `false` 471 * `readableAll` {boolean} For IPC servers makes the pipe readable 472 for all users. **Default:** `false`. 473 * `writableAll` {boolean} For IPC servers makes the pipe writable 474 for all users. **Default:** `false`. 475 * `ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will 476 disable dual-stack support, i.e., binding to host `::` won't make 477 `0.0.0.0` be bound. **Default:** `false`. 478 * `signal` {AbortSignal} An AbortSignal that may be used to close a listening server. 479* `callback` {Function} 480 functions. 481* Returns: {net.Server} 482 483If `port` is specified, it behaves the same as 484[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`]. 485Otherwise, if `path` is specified, it behaves the same as 486[`server.listen(path[, backlog][, callback])`][`server.listen(path)`]. 487If none of them is specified, an error will be thrown. 488 489If `exclusive` is `false` (default), then cluster workers will use the same 490underlying handle, allowing connection handling duties to be shared. When 491`exclusive` is `true`, the handle is not shared, and attempted port sharing 492results in an error. An example which listens on an exclusive port is 493shown below. 494 495```js 496server.listen({ 497 host: 'localhost', 498 port: 80, 499 exclusive: true, 500}); 501``` 502 503When `exclusive` is `true` and the underlying handle is shared, it is 504possible that several workers query a handle with different backlogs. 505In this case, the first `backlog` passed to the master process will be used. 506 507Starting an IPC server as root may cause the server path to be inaccessible for 508unprivileged users. Using `readableAll` and `writableAll` will make the server 509accessible for all users. 510 511If the `signal` option is enabled, calling `.abort()` on the corresponding 512`AbortController` is similar to calling `.close()` on the server: 513 514```js 515const controller = new AbortController(); 516server.listen({ 517 host: 'localhost', 518 port: 80, 519 signal: controller.signal, 520}); 521// Later, when you want to close the server. 522controller.abort(); 523``` 524 525#### `server.listen(path[, backlog][, callback])` 526 527<!-- YAML 528added: v0.1.90 529--> 530 531* `path` {string} Path the server should listen to. See 532 [Identifying paths for IPC connections][]. 533* `backlog` {number} Common parameter of [`server.listen()`][] functions. 534* `callback` {Function}. 535* Returns: {net.Server} 536 537Start an [IPC][] server listening for connections on the given `path`. 538 539#### `server.listen([port[, host[, backlog]]][, callback])` 540 541<!-- YAML 542added: v0.1.90 543--> 544 545* `port` {number} 546* `host` {string} 547* `backlog` {number} Common parameter of [`server.listen()`][] functions. 548* `callback` {Function}. 549* Returns: {net.Server} 550 551Start a TCP server listening for connections on the given `port` and `host`. 552 553If `port` is omitted or is 0, the operating system will assign an arbitrary 554unused port, which can be retrieved by using `server.address().port` 555after the [`'listening'`][] event has been emitted. 556 557If `host` is omitted, the server will accept connections on the 558[unspecified IPv6 address][] (`::`) when IPv6 is available, or the 559[unspecified IPv4 address][] (`0.0.0.0`) otherwise. 560 561In most operating systems, listening to the [unspecified IPv6 address][] (`::`) 562may cause the `net.Server` to also listen on the [unspecified IPv4 address][] 563(`0.0.0.0`). 564 565### `server.listening` 566 567<!-- YAML 568added: v5.7.0 569--> 570 571* {boolean} Indicates whether or not the server is listening for connections. 572 573### `server.maxConnections` 574 575<!-- YAML 576added: v0.2.0 577--> 578 579* {integer} 580 581Set this property to reject connections when the server's connection count gets 582high. 583 584It is not recommended to use this option once a socket has been sent to a child 585with [`child_process.fork()`][]. 586 587### `server.ref()` 588 589<!-- YAML 590added: v0.9.1 591--> 592 593* Returns: {net.Server} 594 595Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will 596_not_ let the program exit if it's the only server left (the default behavior). 597If the server is `ref`ed calling `ref()` again will have no effect. 598 599### `server.unref()` 600 601<!-- YAML 602added: v0.9.1 603--> 604 605* Returns: {net.Server} 606 607Calling `unref()` on a server will allow the program to exit if this is the only 608active server in the event system. If the server is already `unref`ed calling 609`unref()` again will have no effect. 610 611## Class: `net.Socket` 612 613<!-- YAML 614added: v0.3.4 615--> 616 617* Extends: {stream.Duplex} 618 619This class is an abstraction of a TCP socket or a streaming [IPC][] endpoint 620(uses named pipes on Windows, and Unix domain sockets otherwise). It is also 621an [`EventEmitter`][]. 622 623A `net.Socket` can be created by the user and used directly to interact with 624a server. For example, it is returned by [`net.createConnection()`][], 625so the user can use it to talk to the server. 626 627It can also be created by Node.js and passed to the user when a connection 628is received. For example, it is passed to the listeners of a 629[`'connection'`][] event emitted on a [`net.Server`][], so the user can use 630it to interact with the client. 631 632### `new net.Socket([options])` 633 634<!-- YAML 635added: v0.3.4 636changes: 637 - version: v15.14.0 638 pr-url: https://github.com/nodejs/node/pull/37735 639 description: AbortSignal support was added. 640--> 641 642* `options` {Object} Available options are: 643 * `fd` {number} If specified, wrap around an existing socket with 644 the given file descriptor, otherwise a new socket will be created. 645 * `allowHalfOpen` {boolean} If set to `false`, then the socket will 646 automatically end the writable side when the readable side ends. See 647 [`net.createServer()`][] and the [`'end'`][] event for details. **Default:** 648 `false`. 649 * `readable` {boolean} Allow reads on the socket when an `fd` is passed, 650 otherwise ignored. **Default:** `false`. 651 * `writable` {boolean} Allow writes on the socket when an `fd` is passed, 652 otherwise ignored. **Default:** `false`. 653 * `signal` {AbortSignal} An Abort signal that may be used to destroy the 654 socket. 655* Returns: {net.Socket} 656 657Creates a new socket object. 658 659The newly created socket can be either a TCP socket or a streaming [IPC][] 660endpoint, depending on what it [`connect()`][`socket.connect()`] to. 661 662### Event: `'close'` 663 664<!-- YAML 665added: v0.1.90 666--> 667 668* `hadError` {boolean} `true` if the socket had a transmission error. 669 670Emitted once the socket is fully closed. The argument `hadError` is a boolean 671which says if the socket was closed due to a transmission error. 672 673### Event: `'connect'` 674 675<!-- YAML 676added: v0.1.90 677--> 678 679Emitted when a socket connection is successfully established. 680See [`net.createConnection()`][]. 681 682### Event: `'data'` 683 684<!-- YAML 685added: v0.1.90 686--> 687 688* {Buffer|string} 689 690Emitted when data is received. The argument `data` will be a `Buffer` or 691`String`. Encoding of data is set by [`socket.setEncoding()`][]. 692 693The data will be lost if there is no listener when a `Socket` 694emits a `'data'` event. 695 696### Event: `'drain'` 697 698<!-- YAML 699added: v0.1.90 700--> 701 702Emitted when the write buffer becomes empty. Can be used to throttle uploads. 703 704See also: the return values of `socket.write()`. 705 706### Event: `'end'` 707 708<!-- YAML 709added: v0.1.90 710--> 711 712Emitted when the other end of the socket signals the end of transmission, thus 713ending the readable side of the socket. 714 715By default (`allowHalfOpen` is `false`) the socket will send an end of 716transmission packet back and destroy its file descriptor once it has written out 717its pending write queue. However, if `allowHalfOpen` is set to `true`, the 718socket will not automatically [`end()`][`socket.end()`] its writable side, 719allowing the user to write arbitrary amounts of data. The user must call 720[`end()`][`socket.end()`] explicitly to close the connection (i.e. sending a 721FIN packet back). 722 723### Event: `'error'` 724 725<!-- YAML 726added: v0.1.90 727--> 728 729* {Error} 730 731Emitted when an error occurs. The `'close'` event will be called directly 732following this event. 733 734### Event: `'lookup'` 735 736<!-- YAML 737added: v0.11.3 738changes: 739 - version: v5.10.0 740 pr-url: https://github.com/nodejs/node/pull/5598 741 description: The `host` parameter is supported now. 742--> 743 744Emitted after resolving the host name but before connecting. 745Not applicable to Unix sockets. 746 747* `err` {Error|null} The error object. See [`dns.lookup()`][]. 748* `address` {string} The IP address. 749* `family` {number|null} The address type. See [`dns.lookup()`][]. 750* `host` {string} The host name. 751 752### Event: `'ready'` 753 754<!-- YAML 755added: v9.11.0 756--> 757 758Emitted when a socket is ready to be used. 759 760Triggered immediately after `'connect'`. 761 762### Event: `'timeout'` 763 764<!-- YAML 765added: v0.1.90 766--> 767 768Emitted if the socket times out from inactivity. This is only to notify that 769the socket has been idle. The user must manually close the connection. 770 771See also: [`socket.setTimeout()`][]. 772 773### `socket.address()` 774 775<!-- YAML 776added: v0.1.90 777changes: 778 - version: v18.4.0 779 pr-url: https://github.com/nodejs/node/pull/43054 780 description: The `family` property now returns a string instead of a number. 781 - version: v18.0.0 782 pr-url: https://github.com/nodejs/node/pull/41431 783 description: The `family` property now returns a number instead of a string. 784--> 785 786* Returns: {Object} 787 788Returns the bound `address`, the address `family` name and `port` of the 789socket as reported by the operating system: 790`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` 791 792### `socket.autoSelectFamilyAttemptedAddresses` 793 794<!-- YAML 795added: v18.18.0 796--> 797 798* {string\[]} 799 800This property is only present if the family autoselection algorithm is enabled in 801[`socket.connect(options)`][] and it is an array of the addresses that have been attempted. 802 803Each address is a string in the form of `$IP:$PORT`. If the connection was successful, 804then the last address is the one that the socket is currently connected to. 805 806### `socket.bufferSize` 807 808<!-- YAML 809added: v0.3.8 810deprecated: 811 - v14.6.0 812--> 813 814> Stability: 0 - Deprecated: Use [`writable.writableLength`][] instead. 815 816* {integer} 817 818This property shows the number of characters buffered for writing. The buffer 819may contain strings whose length after encoding is not yet known. So this number 820is only an approximation of the number of bytes in the buffer. 821 822`net.Socket` has the property that `socket.write()` always works. This is to 823help users get up and running quickly. The computer cannot always keep up 824with the amount of data that is written to a socket. The network connection 825simply might be too slow. Node.js will internally queue up the data written to a 826socket and send it out over the wire when it is possible. 827 828The consequence of this internal buffering is that memory may grow. 829Users who experience large or growing `bufferSize` should attempt to 830"throttle" the data flows in their program with 831[`socket.pause()`][] and [`socket.resume()`][]. 832 833### `socket.bytesRead` 834 835<!-- YAML 836added: v0.5.3 837--> 838 839* {integer} 840 841The amount of received bytes. 842 843### `socket.bytesWritten` 844 845<!-- YAML 846added: v0.5.3 847--> 848 849* {integer} 850 851The amount of bytes sent. 852 853### `socket.connect()` 854 855Initiate a connection on a given socket. 856 857Possible signatures: 858 859* [`socket.connect(options[, connectListener])`][`socket.connect(options)`] 860* [`socket.connect(path[, connectListener])`][`socket.connect(path)`] 861 for [IPC][] connections. 862* [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`] 863 for TCP connections. 864* Returns: {net.Socket} The socket itself. 865 866This function is asynchronous. When the connection is established, the 867[`'connect'`][] event will be emitted. If there is a problem connecting, 868instead of a [`'connect'`][] event, an [`'error'`][] event will be emitted with 869the error passed to the [`'error'`][] listener. 870The last parameter `connectListener`, if supplied, will be added as a listener 871for the [`'connect'`][] event **once**. 872 873This function should only be used for reconnecting a socket after 874`'close'` has been emitted or otherwise it may lead to undefined 875behavior. 876 877#### `socket.connect(options[, connectListener])` 878 879<!-- YAML 880added: v0.1.90 881changes: 882 - version: v18.18.0 883 pr-url: https://github.com/nodejs/node/pull/45777 884 description: The default value for autoSelectFamily option can be changed 885 at runtime using `setDefaultAutoSelectFamily` or via the 886 command line option `--enable-network-family-autoselection`. 887 - version: v18.13.0 888 pr-url: https://github.com/nodejs/node/pull/44731 889 description: Added the `autoSelectFamily` option. 890 - version: v17.7.0 891 pr-url: https://github.com/nodejs/node/pull/41310 892 description: The `noDelay`, `keepAlive`, and `keepAliveInitialDelay` 893 options are supported now. 894 - version: v12.10.0 895 pr-url: https://github.com/nodejs/node/pull/25436 896 description: Added `onread` option. 897 - version: v6.0.0 898 pr-url: https://github.com/nodejs/node/pull/6021 899 description: The `hints` option defaults to `0` in all cases now. 900 Previously, in the absence of the `family` option it would 901 default to `dns.ADDRCONFIG | dns.V4MAPPED`. 902 - version: v5.11.0 903 pr-url: https://github.com/nodejs/node/pull/6000 904 description: The `hints` option is supported now. 905--> 906 907* `options` {Object} 908* `connectListener` {Function} Common parameter of [`socket.connect()`][] 909 methods. Will be added as a listener for the [`'connect'`][] event once. 910* Returns: {net.Socket} The socket itself. 911 912Initiate a connection on a given socket. Normally this method is not needed, 913the socket should be created and opened with [`net.createConnection()`][]. Use 914this only when implementing a custom Socket. 915 916For TCP connections, available `options` are: 917 918* `port` {number} Required. Port the socket should connect to. 919* `host` {string} Host the socket should connect to. **Default:** `'localhost'`. 920* `localAddress` {string} Local address the socket should connect from. 921* `localPort` {number} Local port the socket should connect from. 922* `family` {number}: Version of IP stack. Must be `4`, `6`, or `0`. The value 923 `0` indicates that both IPv4 and IPv6 addresses are allowed. **Default:** `0`. 924* `hints` {number} Optional [`dns.lookup()` hints][]. 925* `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][]. 926* `noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately 927 after the socket is established. **Default:** `false`. 928* `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket 929 immediately after the connection is established, similarly on what is done in 930 [`socket.setKeepAlive([enable][, initialDelay])`][`socket.setKeepAlive(enable, initialDelay)`]. 931 **Default:** `false`. 932* `keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before 933 the first keepalive probe is sent on an idle socket.**Default:** `0`. 934* `autoSelectFamily` {boolean}: If set to `true`, it enables a family autodetection algorithm 935 that loosely implements section 5 of [RFC 8305][]. 936 The `all` option passed to lookup is set to `true` and the sockets attempts to connect to all 937 obtained IPv6 and IPv4 addresses, in sequence, until a connection is established. 938 The first returned AAAA address is tried first, then the first returned A address, 939 then the second returned AAAA address and so on. 940 Each connection attempt is given the amount of time specified by the `autoSelectFamilyAttemptTimeout` 941 option before timing out and trying the next address. 942 Ignored if the `family` option is not `0` or if `localAddress` is set. 943 Connection errors are not emitted if at least one connection succeeds. 944 **Default:** initially `false`, but it can be changed at runtime using [`net.setDefaultAutoSelectFamily(value)`][] 945 or via the command line option `--enable-network-family-autoselection`. 946* `autoSelectFamilyAttemptTimeout` {number}: The amount of time in milliseconds to wait 947 for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. 948 If set to a positive integer less than `10`, then the value `10` will be used instead. 949 **Default:** initially `250`, but it can be changed at runtime using [`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`][] 950 951For [IPC][] connections, available `options` are: 952 953* `path` {string} Required. Path the client should connect to. 954 See [Identifying paths for IPC connections][]. If provided, the TCP-specific 955 options above are ignored. 956 957For both types, available `options` include: 958 959* `onread` {Object} If specified, incoming data is stored in a single `buffer` 960 and passed to the supplied `callback` when data arrives on the socket. 961 This will cause the streaming functionality to not provide any data. 962 The socket will emit events like `'error'`, `'end'`, and `'close'` 963 as usual. Methods like `pause()` and `resume()` will also behave as 964 expected. 965 * `buffer` {Buffer|Uint8Array|Function} Either a reusable chunk of memory to 966 use for storing incoming data or a function that returns such. 967 * `callback` {Function} This function is called for every chunk of incoming 968 data. Two arguments are passed to it: the number of bytes written to 969 `buffer` and a reference to `buffer`. Return `false` from this function to 970 implicitly `pause()` the socket. This function will be executed in the 971 global context. 972 973Following is an example of a client using the `onread` option: 974 975```js 976const net = require('node:net'); 977net.connect({ 978 port: 80, 979 onread: { 980 // Reuses a 4KiB Buffer for every read from the socket. 981 buffer: Buffer.alloc(4 * 1024), 982 callback: function(nread, buf) { 983 // Received data is available in `buf` from 0 to `nread`. 984 console.log(buf.toString('utf8', 0, nread)); 985 }, 986 }, 987}); 988``` 989 990#### `socket.connect(path[, connectListener])` 991 992* `path` {string} Path the client should connect to. See 993 [Identifying paths for IPC connections][]. 994* `connectListener` {Function} Common parameter of [`socket.connect()`][] 995 methods. Will be added as a listener for the [`'connect'`][] event once. 996* Returns: {net.Socket} The socket itself. 997 998Initiate an [IPC][] connection on the given socket. 999 1000Alias to 1001[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 1002called with `{ path: path }` as `options`. 1003 1004#### `socket.connect(port[, host][, connectListener])` 1005 1006<!-- YAML 1007added: v0.1.90 1008--> 1009 1010* `port` {number} Port the client should connect to. 1011* `host` {string} Host the client should connect to. 1012* `connectListener` {Function} Common parameter of [`socket.connect()`][] 1013 methods. Will be added as a listener for the [`'connect'`][] event once. 1014* Returns: {net.Socket} The socket itself. 1015 1016Initiate a TCP connection on the given socket. 1017 1018Alias to 1019[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 1020called with `{port: port, host: host}` as `options`. 1021 1022### `socket.connecting` 1023 1024<!-- YAML 1025added: v6.1.0 1026--> 1027 1028* {boolean} 1029 1030If `true`, 1031[`socket.connect(options[, connectListener])`][`socket.connect(options)`] was 1032called and has not yet finished. It will stay `true` until the socket becomes 1033connected, then it is set to `false` and the `'connect'` event is emitted. Note 1034that the 1035[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 1036callback is a listener for the `'connect'` event. 1037 1038### `socket.destroy([error])` 1039 1040<!-- YAML 1041added: v0.1.90 1042--> 1043 1044* `error` {Object} 1045* Returns: {net.Socket} 1046 1047Ensures that no more I/O activity happens on this socket. 1048Destroys the stream and closes the connection. 1049 1050See [`writable.destroy()`][] for further details. 1051 1052### `socket.destroyed` 1053 1054* {boolean} Indicates if the connection is destroyed or not. Once a 1055 connection is destroyed no further data can be transferred using it. 1056 1057See [`writable.destroyed`][] for further details. 1058 1059### `socket.destroySoon()` 1060 1061<!-- YAML 1062added: v0.3.4 1063--> 1064 1065Destroys the socket after all data is written. If the `'finish'` event was 1066already emitted the socket is destroyed immediately. If the socket is still 1067writable it implicitly calls `socket.end()`. 1068 1069### `socket.end([data[, encoding]][, callback])` 1070 1071<!-- YAML 1072added: v0.1.90 1073--> 1074 1075* `data` {string|Buffer|Uint8Array} 1076* `encoding` {string} Only used when data is `string`. **Default:** `'utf8'`. 1077* `callback` {Function} Optional callback for when the socket is finished. 1078* Returns: {net.Socket} The socket itself. 1079 1080Half-closes the socket. i.e., it sends a FIN packet. It is possible the 1081server will still send some data. 1082 1083See [`writable.end()`][] for further details. 1084 1085### `socket.localAddress` 1086 1087<!-- YAML 1088added: v0.9.6 1089--> 1090 1091* {string} 1092 1093The string representation of the local IP address the remote client is 1094connecting on. For example, in a server listening on `'0.0.0.0'`, if a client 1095connects on `'192.168.1.1'`, the value of `socket.localAddress` would be 1096`'192.168.1.1'`. 1097 1098### `socket.localPort` 1099 1100<!-- YAML 1101added: v0.9.6 1102--> 1103 1104* {integer} 1105 1106The numeric representation of the local port. For example, `80` or `21`. 1107 1108### `socket.localFamily` 1109 1110<!-- YAML 1111added: v18.8.0 1112--> 1113 1114* {string} 1115 1116The string representation of the local IP family. `'IPv4'` or `'IPv6'`. 1117 1118### `socket.pause()` 1119 1120* Returns: {net.Socket} The socket itself. 1121 1122Pauses the reading of data. That is, [`'data'`][] events will not be emitted. 1123Useful to throttle back an upload. 1124 1125### `socket.pending` 1126 1127<!-- YAML 1128added: 1129 - v11.2.0 1130 - v10.16.0 1131--> 1132 1133* {boolean} 1134 1135This is `true` if the socket is not connected yet, either because `.connect()` 1136has not yet been called or because it is still in the process of connecting 1137(see [`socket.connecting`][]). 1138 1139### `socket.ref()` 1140 1141<!-- YAML 1142added: v0.9.1 1143--> 1144 1145* Returns: {net.Socket} The socket itself. 1146 1147Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will 1148_not_ let the program exit if it's the only socket left (the default behavior). 1149If the socket is `ref`ed calling `ref` again will have no effect. 1150 1151### `socket.remoteAddress` 1152 1153<!-- YAML 1154added: v0.5.10 1155--> 1156 1157* {string} 1158 1159The string representation of the remote IP address. For example, 1160`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if 1161the socket is destroyed (for example, if the client disconnected). 1162 1163### `socket.remoteFamily` 1164 1165<!-- YAML 1166added: v0.11.14 1167--> 1168 1169* {string} 1170 1171The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if 1172the socket is destroyed (for example, if the client disconnected). 1173 1174### `socket.remotePort` 1175 1176<!-- YAML 1177added: v0.5.10 1178--> 1179 1180* {integer} 1181 1182The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if 1183the socket is destroyed (for example, if the client disconnected). 1184 1185### `socket.resetAndDestroy()` 1186 1187<!-- YAML 1188added: v18.3.0 1189--> 1190 1191* Returns: {net.Socket} 1192 1193Close the TCP connection by sending an RST packet and destroy the stream. 1194If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. 1195Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. 1196If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. 1197 1198### `socket.resume()` 1199 1200* Returns: {net.Socket} The socket itself. 1201 1202Resumes reading after a call to [`socket.pause()`][]. 1203 1204### `socket.setEncoding([encoding])` 1205 1206<!-- YAML 1207added: v0.1.90 1208--> 1209 1210* `encoding` {string} 1211* Returns: {net.Socket} The socket itself. 1212 1213Set the encoding for the socket as a [Readable Stream][]. See 1214[`readable.setEncoding()`][] for more information. 1215 1216### `socket.setKeepAlive([enable][, initialDelay])` 1217 1218<!-- YAML 1219added: v0.1.92 1220changes: 1221 - version: 1222 - v13.12.0 1223 - v12.17.0 1224 pr-url: https://github.com/nodejs/node/pull/32204 1225 description: New defaults for `TCP_KEEPCNT` and `TCP_KEEPINTVL` socket options were added. 1226--> 1227 1228* `enable` {boolean} **Default:** `false` 1229* `initialDelay` {number} **Default:** `0` 1230* Returns: {net.Socket} The socket itself. 1231 1232Enable/disable keep-alive functionality, and optionally set the initial 1233delay before the first keepalive probe is sent on an idle socket. 1234 1235Set `initialDelay` (in milliseconds) to set the delay between the last 1236data packet received and the first keepalive probe. Setting `0` for 1237`initialDelay` will leave the value unchanged from the default 1238(or previous) setting. 1239 1240Enabling the keep-alive functionality will set the following socket options: 1241 1242* `SO_KEEPALIVE=1` 1243* `TCP_KEEPIDLE=initialDelay` 1244* `TCP_KEEPCNT=10` 1245* `TCP_KEEPINTVL=1` 1246 1247### `socket.setNoDelay([noDelay])` 1248 1249<!-- YAML 1250added: v0.1.90 1251--> 1252 1253* `noDelay` {boolean} **Default:** `true` 1254* Returns: {net.Socket} The socket itself. 1255 1256Enable/disable the use of Nagle's algorithm. 1257 1258When a TCP connection is created, it will have Nagle's algorithm enabled. 1259 1260Nagle's algorithm delays data before it is sent via the network. It attempts 1261to optimize throughput at the expense of latency. 1262 1263Passing `true` for `noDelay` or not passing an argument will disable Nagle's 1264algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's 1265algorithm. 1266 1267### `socket.setTimeout(timeout[, callback])` 1268 1269<!-- YAML 1270added: v0.1.90 1271changes: 1272 - version: v18.0.0 1273 pr-url: https://github.com/nodejs/node/pull/41678 1274 description: Passing an invalid callback to the `callback` argument 1275 now throws `ERR_INVALID_ARG_TYPE` instead of 1276 `ERR_INVALID_CALLBACK`. 1277--> 1278 1279* `timeout` {number} 1280* `callback` {Function} 1281* Returns: {net.Socket} The socket itself. 1282 1283Sets the socket to timeout after `timeout` milliseconds of inactivity on 1284the socket. By default `net.Socket` do not have a timeout. 1285 1286When an idle timeout is triggered the socket will receive a [`'timeout'`][] 1287event but the connection will not be severed. The user must manually call 1288[`socket.end()`][] or [`socket.destroy()`][] to end the connection. 1289 1290```js 1291socket.setTimeout(3000); 1292socket.on('timeout', () => { 1293 console.log('socket timeout'); 1294 socket.end(); 1295}); 1296``` 1297 1298If `timeout` is 0, then the existing idle timeout is disabled. 1299 1300The optional `callback` parameter will be added as a one-time listener for the 1301[`'timeout'`][] event. 1302 1303### `socket.timeout` 1304 1305<!-- YAML 1306added: v10.7.0 1307--> 1308 1309* {number|undefined} 1310 1311The socket timeout in milliseconds as set by [`socket.setTimeout()`][]. 1312It is `undefined` if a timeout has not been set. 1313 1314### `socket.unref()` 1315 1316<!-- YAML 1317added: v0.9.1 1318--> 1319 1320* Returns: {net.Socket} The socket itself. 1321 1322Calling `unref()` on a socket will allow the program to exit if this is the only 1323active socket in the event system. If the socket is already `unref`ed calling 1324`unref()` again will have no effect. 1325 1326### `socket.write(data[, encoding][, callback])` 1327 1328<!-- YAML 1329added: v0.1.90 1330--> 1331 1332* `data` {string|Buffer|Uint8Array} 1333* `encoding` {string} Only used when data is `string`. **Default:** `utf8`. 1334* `callback` {Function} 1335* Returns: {boolean} 1336 1337Sends data on the socket. The second parameter specifies the encoding in the 1338case of a string. It defaults to UTF8 encoding. 1339 1340Returns `true` if the entire data was flushed successfully to the kernel 1341buffer. Returns `false` if all or part of the data was queued in user memory. 1342[`'drain'`][] will be emitted when the buffer is again free. 1343 1344The optional `callback` parameter will be executed when the data is finally 1345written out, which may not be immediately. 1346 1347See `Writable` stream [`write()`][stream_writable_write] method for more 1348information. 1349 1350### `socket.readyState` 1351 1352<!-- YAML 1353added: v0.5.0 1354--> 1355 1356* {string} 1357 1358This property represents the state of the connection as a string. 1359 1360* If the stream is connecting `socket.readyState` is `opening`. 1361* If the stream is readable and writable, it is `open`. 1362* If the stream is readable and not writable, it is `readOnly`. 1363* If the stream is not readable and writable, it is `writeOnly`. 1364 1365## `net.connect()` 1366 1367Aliases to 1368[`net.createConnection()`][`net.createConnection()`]. 1369 1370Possible signatures: 1371 1372* [`net.connect(options[, connectListener])`][`net.connect(options)`] 1373* [`net.connect(path[, connectListener])`][`net.connect(path)`] for [IPC][] 1374 connections. 1375* [`net.connect(port[, host][, connectListener])`][`net.connect(port, host)`] 1376 for TCP connections. 1377 1378### `net.connect(options[, connectListener])` 1379 1380<!-- YAML 1381added: v0.7.0 1382--> 1383 1384* `options` {Object} 1385* `connectListener` {Function} 1386* Returns: {net.Socket} 1387 1388Alias to 1389[`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. 1390 1391### `net.connect(path[, connectListener])` 1392 1393<!-- YAML 1394added: v0.1.90 1395--> 1396 1397* `path` {string} 1398* `connectListener` {Function} 1399* Returns: {net.Socket} 1400 1401Alias to 1402[`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]. 1403 1404### `net.connect(port[, host][, connectListener])` 1405 1406<!-- YAML 1407added: v0.1.90 1408--> 1409 1410* `port` {number} 1411* `host` {string} 1412* `connectListener` {Function} 1413* Returns: {net.Socket} 1414 1415Alias to 1416[`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`]. 1417 1418## `net.createConnection()` 1419 1420A factory function, which creates a new [`net.Socket`][], 1421immediately initiates connection with [`socket.connect()`][], 1422then returns the `net.Socket` that starts the connection. 1423 1424When the connection is established, a [`'connect'`][] event will be emitted 1425on the returned socket. The last parameter `connectListener`, if supplied, 1426will be added as a listener for the [`'connect'`][] event **once**. 1427 1428Possible signatures: 1429 1430* [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`] 1431* [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`] 1432 for [IPC][] connections. 1433* [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`] 1434 for TCP connections. 1435 1436The [`net.connect()`][] function is an alias to this function. 1437 1438### `net.createConnection(options[, connectListener])` 1439 1440<!-- YAML 1441added: v0.1.90 1442--> 1443 1444* `options` {Object} Required. Will be passed to both the 1445 [`new net.Socket([options])`][`new net.Socket(options)`] call and the 1446 [`socket.connect(options[, connectListener])`][`socket.connect(options)`] 1447 method. 1448* `connectListener` {Function} Common parameter of the 1449 [`net.createConnection()`][] functions. If supplied, will be added as 1450 a listener for the [`'connect'`][] event on the returned socket once. 1451* Returns: {net.Socket} The newly created socket used to start the connection. 1452 1453For available options, see 1454[`new net.Socket([options])`][`new net.Socket(options)`] 1455and [`socket.connect(options[, connectListener])`][`socket.connect(options)`]. 1456 1457Additional options: 1458 1459* `timeout` {number} If set, will be used to call 1460 [`socket.setTimeout(timeout)`][] after the socket is created, but before 1461 it starts the connection. 1462 1463Following is an example of a client of the echo server described 1464in the [`net.createServer()`][] section: 1465 1466```js 1467const net = require('node:net'); 1468const client = net.createConnection({ port: 8124 }, () => { 1469 // 'connect' listener. 1470 console.log('connected to server!'); 1471 client.write('world!\r\n'); 1472}); 1473client.on('data', (data) => { 1474 console.log(data.toString()); 1475 client.end(); 1476}); 1477client.on('end', () => { 1478 console.log('disconnected from server'); 1479}); 1480``` 1481 1482To connect on the socket `/tmp/echo.sock`: 1483 1484```js 1485const client = net.createConnection({ path: '/tmp/echo.sock' }); 1486``` 1487 1488### `net.createConnection(path[, connectListener])` 1489 1490<!-- YAML 1491added: v0.1.90 1492--> 1493 1494* `path` {string} Path the socket should connect to. Will be passed to 1495 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 1496 See [Identifying paths for IPC connections][]. 1497* `connectListener` {Function} Common parameter of the 1498 [`net.createConnection()`][] functions, an "once" listener for the 1499 `'connect'` event on the initiating socket. Will be passed to 1500 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 1501* Returns: {net.Socket} The newly created socket used to start the connection. 1502 1503Initiates an [IPC][] connection. 1504 1505This function creates a new [`net.Socket`][] with all options set to default, 1506immediately initiates connection with 1507[`socket.connect(path[, connectListener])`][`socket.connect(path)`], 1508then returns the `net.Socket` that starts the connection. 1509 1510### `net.createConnection(port[, host][, connectListener])` 1511 1512<!-- YAML 1513added: v0.1.90 1514--> 1515 1516* `port` {number} Port the socket should connect to. Will be passed to 1517 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1518* `host` {string} Host the socket should connect to. Will be passed to 1519 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1520 **Default:** `'localhost'`. 1521* `connectListener` {Function} Common parameter of the 1522 [`net.createConnection()`][] functions, an "once" listener for the 1523 `'connect'` event on the initiating socket. Will be passed to 1524 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1525* Returns: {net.Socket} The newly created socket used to start the connection. 1526 1527Initiates a TCP connection. 1528 1529This function creates a new [`net.Socket`][] with all options set to default, 1530immediately initiates connection with 1531[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`], 1532then returns the `net.Socket` that starts the connection. 1533 1534## `net.createServer([options][, connectionListener])` 1535 1536<!-- YAML 1537added: v0.5.0 1538changes: 1539 - version: v18.17.0 1540 pr-url: https://github.com/nodejs/node/pull/47405 1541 description: The `highWaterMark` option is supported now. 1542 - version: 1543 - v17.7.0 1544 - v16.15.0 1545 pr-url: https://github.com/nodejs/node/pull/41310 1546 description: The `noDelay`, `keepAlive`, and `keepAliveInitialDelay` 1547 options are supported now. 1548--> 1549 1550* `options` {Object} 1551 * `allowHalfOpen` {boolean} If set to `false`, then the socket will 1552 automatically end the writable side when the readable side ends. 1553 **Default:** `false`. 1554 * `highWaterMark` {number} Optionally overrides all [`net.Socket`][]s' 1555 `readableHighWaterMark` and `writableHighWaterMark`. 1556 **Default:** See [`stream.getDefaultHighWaterMark()`][]. 1557 * `pauseOnConnect` {boolean} Indicates whether the socket should be 1558 paused on incoming connections. **Default:** `false`. 1559 * `noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately 1560 after a new incoming connection is received. **Default:** `false`. 1561 * `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket 1562 immediately after a new incoming connection is received, similarly on what is done in 1563 [`socket.setKeepAlive([enable][, initialDelay])`][`socket.setKeepAlive(enable, initialDelay)`]. 1564 **Default:** `false`. 1565 * `keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before 1566 the first keepalive probe is sent on an idle socket.**Default:** `0`. 1567 1568* `connectionListener` {Function} Automatically set as a listener for the 1569 [`'connection'`][] event. 1570 1571* Returns: {net.Server} 1572 1573Creates a new TCP or [IPC][] server. 1574 1575If `allowHalfOpen` is set to `true`, when the other end of the socket 1576signals the end of transmission, the server will only send back the end of 1577transmission when [`socket.end()`][] is explicitly called. For example, in the 1578context of TCP, when a FIN packed is received, a FIN packed is sent 1579back only when [`socket.end()`][] is explicitly called. Until then the 1580connection is half-closed (non-readable but still writable). See [`'end'`][] 1581event and [RFC 1122][half-closed] (section 4.2.2.13) for more information. 1582 1583If `pauseOnConnect` is set to `true`, then the socket associated with each 1584incoming connection will be paused, and no data will be read from its handle. 1585This allows connections to be passed between processes without any data being 1586read by the original process. To begin reading data from a paused socket, call 1587[`socket.resume()`][]. 1588 1589The server can be a TCP server or an [IPC][] server, depending on what it 1590[`listen()`][`server.listen()`] to. 1591 1592Here is an example of a TCP echo server which listens for connections 1593on port 8124: 1594 1595```js 1596const net = require('node:net'); 1597const server = net.createServer((c) => { 1598 // 'connection' listener. 1599 console.log('client connected'); 1600 c.on('end', () => { 1601 console.log('client disconnected'); 1602 }); 1603 c.write('hello\r\n'); 1604 c.pipe(c); 1605}); 1606server.on('error', (err) => { 1607 throw err; 1608}); 1609server.listen(8124, () => { 1610 console.log('server bound'); 1611}); 1612``` 1613 1614Test this by using `telnet`: 1615 1616```console 1617$ telnet localhost 8124 1618``` 1619 1620To listen on the socket `/tmp/echo.sock`: 1621 1622```js 1623server.listen('/tmp/echo.sock', () => { 1624 console.log('server bound'); 1625}); 1626``` 1627 1628Use `nc` to connect to a Unix domain socket server: 1629 1630```console 1631$ nc -U /tmp/echo.sock 1632``` 1633 1634## `net.getDefaultAutoSelectFamily()` 1635 1636<!-- YAML 1637added: v19.4.0 1638--> 1639 1640Gets the current default value of the `autoSelectFamily` option of [`socket.connect(options)`][]. 1641 1642* Returns: {boolean} The current default value of the `autoSelectFamily` option. 1643 1644## `net.setDefaultAutoSelectFamily(value)` 1645 1646<!-- YAML 1647added: v19.4.0 1648--> 1649 1650Sets the default value of the `autoSelectFamily` option of [`socket.connect(options)`][]. 1651 1652* `value` {boolean} The new default value. The initial default value is `false`. 1653 1654## `net.getDefaultAutoSelectFamilyAttemptTimeout()` 1655 1656<!-- YAML 1657added: v18.18.0 1658--> 1659 1660Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of [`socket.connect(options)`][]. 1661 1662* Returns: {number} The current default value of the `autoSelectFamilyAttemptTimeout` option. 1663 1664## `net.setDefaultAutoSelectFamilyAttemptTimeout(value)` 1665 1666<!-- YAML 1667added: v18.18.0 1668--> 1669 1670Sets the default value of the `autoSelectFamilyAttemptTimeout` option of [`socket.connect(options)`][]. 1671 1672* `value` {number} The new default value, which must be a positive number. If the number is less than `10`, 1673 the value `10` is used instead. The initial default value is `250`. 1674 1675## `net.isIP(input)` 1676 1677<!-- YAML 1678added: v0.3.0 1679--> 1680 1681* `input` {string} 1682* Returns: {integer} 1683 1684Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 1685address in [dot-decimal notation][] with no leading zeroes. Otherwise, returns 1686`0`. 1687 1688```js 1689net.isIP('::1'); // returns 6 1690net.isIP('127.0.0.1'); // returns 4 1691net.isIP('127.000.000.001'); // returns 0 1692net.isIP('127.0.0.1/24'); // returns 0 1693net.isIP('fhqwhgads'); // returns 0 1694``` 1695 1696## `net.isIPv4(input)` 1697 1698<!-- YAML 1699added: v0.3.0 1700--> 1701 1702* `input` {string} 1703* Returns: {boolean} 1704 1705Returns `true` if `input` is an IPv4 address in [dot-decimal notation][] with no 1706leading zeroes. Otherwise, returns `false`. 1707 1708```js 1709net.isIPv4('127.0.0.1'); // returns true 1710net.isIPv4('127.000.000.001'); // returns false 1711net.isIPv4('127.0.0.1/24'); // returns false 1712net.isIPv4('fhqwhgads'); // returns false 1713``` 1714 1715## `net.isIPv6(input)` 1716 1717<!-- YAML 1718added: v0.3.0 1719--> 1720 1721* `input` {string} 1722* Returns: {boolean} 1723 1724Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. 1725 1726```js 1727net.isIPv6('::1'); // returns true 1728net.isIPv6('fhqwhgads'); // returns false 1729``` 1730 1731[IPC]: #ipc-support 1732[Identifying paths for IPC connections]: #identifying-paths-for-ipc-connections 1733[RFC 8305]: https://www.rfc-editor.org/rfc/rfc8305.txt 1734[Readable Stream]: stream.md#class-streamreadable 1735[`'close'`]: #event-close 1736[`'connect'`]: #event-connect 1737[`'connection'`]: #event-connection 1738[`'data'`]: #event-data 1739[`'drain'`]: #event-drain 1740[`'end'`]: #event-end 1741[`'error'`]: #event-error_1 1742[`'listening'`]: #event-listening 1743[`'timeout'`]: #event-timeout 1744[`EventEmitter`]: events.md#class-eventemitter 1745[`child_process.fork()`]: child_process.md#child_processforkmodulepath-args-options 1746[`dns.lookup()`]: dns.md#dnslookuphostname-options-callback 1747[`dns.lookup()` hints]: dns.md#supported-getaddrinfo-flags 1748[`net.Server`]: #class-netserver 1749[`net.Socket`]: #class-netsocket 1750[`net.connect()`]: #netconnect 1751[`net.connect(options)`]: #netconnectoptions-connectlistener 1752[`net.connect(path)`]: #netconnectpath-connectlistener 1753[`net.connect(port, host)`]: #netconnectport-host-connectlistener 1754[`net.createConnection()`]: #netcreateconnection 1755[`net.createConnection(options)`]: #netcreateconnectionoptions-connectlistener 1756[`net.createConnection(path)`]: #netcreateconnectionpath-connectlistener 1757[`net.createConnection(port, host)`]: #netcreateconnectionport-host-connectlistener 1758[`net.createServer()`]: #netcreateserveroptions-connectionlistener 1759[`net.setDefaultAutoSelectFamily(value)`]: #netsetdefaultautoselectfamilyvalue 1760[`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`]: #netsetdefaultautoselectfamilyattempttimeoutvalue 1761[`new net.Socket(options)`]: #new-netsocketoptions 1762[`readable.setEncoding()`]: stream.md#readablesetencodingencoding 1763[`server.close()`]: #serverclosecallback 1764[`server.listen()`]: #serverlisten 1765[`server.listen(handle)`]: #serverlistenhandle-backlog-callback 1766[`server.listen(options)`]: #serverlistenoptions-callback 1767[`server.listen(path)`]: #serverlistenpath-backlog-callback 1768[`server.listen(port)`]: #serverlistenport-host-backlog-callback 1769[`socket(7)`]: https://man7.org/linux/man-pages/man7/socket.7.html 1770[`socket.connect()`]: #socketconnect 1771[`socket.connect(options)`]: #socketconnectoptions-connectlistener 1772[`socket.connect(path)`]: #socketconnectpath-connectlistener 1773[`socket.connect(port)`]: #socketconnectport-host-connectlistener 1774[`socket.connecting`]: #socketconnecting 1775[`socket.destroy()`]: #socketdestroyerror 1776[`socket.end()`]: #socketenddata-encoding-callback 1777[`socket.pause()`]: #socketpause 1778[`socket.resume()`]: #socketresume 1779[`socket.setEncoding()`]: #socketsetencodingencoding 1780[`socket.setKeepAlive(enable, initialDelay)`]: #socketsetkeepaliveenable-initialdelay 1781[`socket.setTimeout()`]: #socketsettimeouttimeout-callback 1782[`socket.setTimeout(timeout)`]: #socketsettimeouttimeout-callback 1783[`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode 1784[`writable.destroy()`]: stream.md#writabledestroyerror 1785[`writable.destroyed`]: stream.md#writabledestroyed 1786[`writable.end()`]: stream.md#writableendchunk-encoding-callback 1787[`writable.writableLength`]: stream.md#writablewritablelength 1788[dot-decimal notation]: https://en.wikipedia.org/wiki/Dot-decimal_notation 1789[half-closed]: https://tools.ietf.org/html/rfc1122 1790[stream_writable_write]: stream.md#writablewritechunk-encoding-callback 1791[unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0 1792[unspecified IPv6 address]: https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address 1793