1# Net 2 3<!--introduced_in=v0.10.0--> 4<!--lint disable maximum-line-length--> 5 6> Stability: 2 - Stable 7 8<!-- source_link=lib/net.js --> 9 10The `net` module provides an asynchronous network API for creating stream-based 11TCP or [IPC][] servers ([`net.createServer()`][]) and clients 12([`net.createConnection()`][]). 13 14It can be accessed using: 15 16```js 17const net = require('net'); 18``` 19 20## IPC support 21 22The `net` module supports IPC with named pipes on Windows, and Unix domain 23sockets on other operating systems. 24 25### Identifying paths for IPC connections 26 27[`net.connect()`][], [`net.createConnection()`][], [`server.listen()`][] and 28[`socket.connect()`][] take a `path` parameter to identify IPC endpoints. 29 30On Unix, the local domain is also known as the Unix domain. The path is a 31filesystem pathname. It gets truncated to an OS-dependent length of 32`sizeof(sockaddr_un.sun_path) - 1`. Typical values are 107 bytes on Linux and 33103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, 34it will unlink the Unix domain socket as well. For example, 35[`net.createServer()`][] may create a Unix domain socket and 36[`server.close()`][] will unlink it. But if a user creates the Unix domain 37socket outside of these abstractions, the user will need to remove it. The same 38applies when a Node.js API creates a Unix domain socket but the program then 39crashes. In short, a Unix domain socket will be visible in the filesystem and 40will persist until unlinked. 41 42On Windows, the local domain is implemented using a named pipe. The path *must* 43refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted, 44but the latter may do some processing of pipe names, such as resolving `..` 45sequences. Despite how it might look, the pipe namespace is flat. Pipes will 46*not persist*. They are removed when the last reference to them is closed. 47Unlike Unix domain sockets, Windows will close and remove the pipe when the 48owning process exits. 49 50JavaScript string escaping requires paths to be specified with extra backslash 51escaping such as: 52 53```js 54net.createServer().listen( 55 path.join('\\\\?\\pipe', process.cwd(), 'myctl')); 56``` 57 58## Class: `net.Server` 59<!-- YAML 60added: v0.1.90 61--> 62 63* Extends: {EventEmitter} 64 65This class is used to create a TCP or [IPC][] server. 66 67### `new net.Server([options][, connectionListener])` 68 69* `options` {Object} See 70 [`net.createServer([options][, connectionListener])`][`net.createServer()`]. 71* `connectionListener` {Function} Automatically set as a listener for the 72 [`'connection'`][] event. 73* Returns: {net.Server} 74 75`net.Server` is an [`EventEmitter`][] with the following events: 76 77### Event: `'close'` 78<!-- YAML 79added: v0.5.0 80--> 81 82Emitted when the server closes. If connections exist, this 83event is not emitted until all connections are ended. 84 85### Event: `'connection'` 86<!-- YAML 87added: v0.1.90 88--> 89 90* {net.Socket} The connection object 91 92Emitted when a new connection is made. `socket` is an instance of 93`net.Socket`. 94 95### Event: `'error'` 96<!-- YAML 97added: v0.1.90 98--> 99 100* {Error} 101 102Emitted when an error occurs. Unlike [`net.Socket`][], the [`'close'`][] 103event will **not** be emitted directly following this event unless 104[`server.close()`][] is manually called. See the example in discussion of 105[`server.listen()`][]. 106 107### Event: `'listening'` 108<!-- YAML 109added: v0.1.90 110--> 111 112Emitted when the server has been bound after calling [`server.listen()`][]. 113 114### `server.address()` 115<!-- YAML 116added: v0.1.90 117--> 118 119* Returns: {Object|string|null} 120 121Returns the bound `address`, the address `family` name, and `port` of the server 122as reported by the operating system if listening on an IP socket 123(useful to find which port was assigned when getting an OS-assigned address): 124`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. 125 126For a server listening on a pipe or Unix domain socket, the name is returned 127as a string. 128 129```js 130const server = net.createServer((socket) => { 131 socket.end('goodbye\n'); 132}).on('error', (err) => { 133 // Handle errors here. 134 throw err; 135}); 136 137// Grab an arbitrary unused port. 138server.listen(() => { 139 console.log('opened server on', server.address()); 140}); 141``` 142 143`server.address()` returns `null` before the `'listening'` event has been 144emitted or after calling `server.close()`. 145 146### `server.close([callback])` 147<!-- YAML 148added: v0.1.90 149--> 150 151* `callback` {Function} Called when the server is closed. 152* Returns: {net.Server} 153 154Stops the server from accepting new connections and keeps existing 155connections. This function is asynchronous, the server is finally closed 156when all connections are ended and the server emits a [`'close'`][] event. 157The optional `callback` will be called once the `'close'` event occurs. Unlike 158that event, it will be called with an `Error` as its only argument if the server 159was not open when it was closed. 160 161### `server.connections` 162<!-- YAML 163added: v0.2.0 164deprecated: v0.9.7 165--> 166 167> Stability: 0 - Deprecated: Use [`server.getConnections()`][] instead. 168 169* {integer|null} 170 171The number of concurrent connections on the server. 172 173This becomes `null` when sending a socket to a child with 174[`child_process.fork()`][]. To poll forks and get current number of active 175connections, use asynchronous [`server.getConnections()`][] instead. 176 177### `server.getConnections(callback)` 178<!-- YAML 179added: v0.9.7 180--> 181 182* `callback` {Function} 183* Returns: {net.Server} 184 185Asynchronously get the number of concurrent connections on the server. Works 186when sockets were sent to forks. 187 188Callback should take two arguments `err` and `count`. 189 190### `server.listen()` 191 192Start a server listening for connections. A `net.Server` can be a TCP or 193an [IPC][] server depending on what it listens to. 194 195Possible signatures: 196 197* [`server.listen(handle[, backlog][, callback])`][`server.listen(handle)`] 198* [`server.listen(options[, callback])`][`server.listen(options)`] 199* [`server.listen(path[, backlog][, callback])`][`server.listen(path)`] 200 for [IPC][] servers 201* <a href="#net_server_listen_port_host_backlog_callback"> 202 <code>server.listen([port[, host[, backlog]]][, callback])</code></a> 203 for TCP servers 204 205This function is asynchronous. When the server starts listening, the 206[`'listening'`][] event will be emitted. The last parameter `callback` 207will be added as a listener for the [`'listening'`][] event. 208 209All `listen()` methods can take a `backlog` parameter to specify the maximum 210length of the queue of pending connections. The actual length will be determined 211by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` 212on Linux. The default value of this parameter is 511 (not 512). 213 214All [`net.Socket`][] are set to `SO_REUSEADDR` (see [`socket(7)`][] for 215details). 216 217The `server.listen()` method can be called again if and only if there was an 218error during the first `server.listen()` call or `server.close()` has been 219called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. 220 221One of the most common errors raised when listening is `EADDRINUSE`. 222This happens when another server is already listening on the requested 223`port`/`path`/`handle`. One way to handle this would be to retry 224after a certain amount of time: 225 226```js 227server.on('error', (e) => { 228 if (e.code === 'EADDRINUSE') { 229 console.log('Address in use, retrying...'); 230 setTimeout(() => { 231 server.close(); 232 server.listen(PORT, HOST); 233 }, 1000); 234 } 235}); 236``` 237 238#### `server.listen(handle[, backlog][, callback])` 239<!-- YAML 240added: v0.5.10 241--> 242 243* `handle` {Object} 244* `backlog` {number} Common parameter of [`server.listen()`][] functions 245* `callback` {Function} 246* Returns: {net.Server} 247 248Start a server listening for connections on a given `handle` that has 249already been bound to a port, a Unix domain socket, or a Windows named pipe. 250 251The `handle` object can be either a server, a socket (anything with an 252underlying `_handle` member), or an object with an `fd` member that is a 253valid file descriptor. 254 255Listening on a file descriptor is not supported on Windows. 256 257#### `server.listen(options[, callback])` 258<!-- YAML 259added: v0.11.14 260changes: 261 - version: v11.4.0 262 pr-url: https://github.com/nodejs/node/pull/23798 263 description: The `ipv6Only` option is supported. 264--> 265 266* `options` {Object} Required. Supports the following properties: 267 * `port` {number} 268 * `host` {string} 269 * `path` {string} Will be ignored if `port` is specified. See 270 [Identifying paths for IPC connections][]. 271 * `backlog` {number} Common parameter of [`server.listen()`][] 272 functions. 273 * `exclusive` {boolean} **Default:** `false` 274 * `readableAll` {boolean} For IPC servers makes the pipe readable 275 for all users. **Default:** `false`. 276 * `writableAll` {boolean} For IPC servers makes the pipe writable 277 for all users. **Default:** `false`. 278 * `ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will 279 disable dual-stack support, i.e., binding to host `::` won't make 280 `0.0.0.0` be bound. **Default:** `false`. 281* `callback` {Function} 282 functions. 283* Returns: {net.Server} 284 285If `port` is specified, it behaves the same as 286<a href="#net_server_listen_port_host_backlog_callback"> 287<code>server.listen([port[, host[, backlog]]][, callback])</code></a>. 288Otherwise, if `path` is specified, it behaves the same as 289[`server.listen(path[, backlog][, callback])`][`server.listen(path)`]. 290If none of them is specified, an error will be thrown. 291 292If `exclusive` is `false` (default), then cluster workers will use the same 293underlying handle, allowing connection handling duties to be shared. When 294`exclusive` is `true`, the handle is not shared, and attempted port sharing 295results in an error. An example which listens on an exclusive port is 296shown below. 297 298```js 299server.listen({ 300 host: 'localhost', 301 port: 80, 302 exclusive: true 303}); 304``` 305 306Starting an IPC server as root may cause the server path to be inaccessible for 307unprivileged users. Using `readableAll` and `writableAll` will make the server 308accessible for all users. 309 310#### `server.listen(path[, backlog][, callback])` 311<!-- YAML 312added: v0.1.90 313--> 314 315* `path` {string} Path the server should listen to. See 316 [Identifying paths for IPC connections][]. 317* `backlog` {number} Common parameter of [`server.listen()`][] functions. 318* `callback` {Function}. 319* Returns: {net.Server} 320 321Start an [IPC][] server listening for connections on the given `path`. 322 323#### `server.listen([port[, host[, backlog]]][, callback])` 324<!-- YAML 325added: v0.1.90 326--> 327 328* `port` {number} 329* `host` {string} 330* `backlog` {number} Common parameter of [`server.listen()`][] functions. 331* `callback` {Function}. 332* Returns: {net.Server} 333 334Start a TCP server listening for connections on the given `port` and `host`. 335 336If `port` is omitted or is 0, the operating system will assign an arbitrary 337unused port, which can be retrieved by using `server.address().port` 338after the [`'listening'`][] event has been emitted. 339 340If `host` is omitted, the server will accept connections on the 341[unspecified IPv6 address][] (`::`) when IPv6 is available, or the 342[unspecified IPv4 address][] (`0.0.0.0`) otherwise. 343 344In most operating systems, listening to the [unspecified IPv6 address][] (`::`) 345may cause the `net.Server` to also listen on the [unspecified IPv4 address][] 346(`0.0.0.0`). 347 348### `server.listening` 349<!-- YAML 350added: v5.7.0 351--> 352 353* {boolean} Indicates whether or not the server is listening for connections. 354 355### `server.maxConnections` 356<!-- YAML 357added: v0.2.0 358--> 359 360* {integer} 361 362Set this property to reject connections when the server's connection count gets 363high. 364 365It is not recommended to use this option once a socket has been sent to a child 366with [`child_process.fork()`][]. 367 368### `server.ref()` 369<!-- YAML 370added: v0.9.1 371--> 372 373* Returns: {net.Server} 374 375Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will 376*not* let the program exit if it's the only server left (the default behavior). 377If the server is `ref`ed calling `ref()` again will have no effect. 378 379### `server.unref()` 380<!-- YAML 381added: v0.9.1 382--> 383 384* Returns: {net.Server} 385 386Calling `unref()` on a server will allow the program to exit if this is the only 387active server in the event system. If the server is already `unref`ed calling 388`unref()` again will have no effect. 389 390## Class: `net.Socket` 391<!-- YAML 392added: v0.3.4 393--> 394 395* Extends: {stream.Duplex} 396 397This class is an abstraction of a TCP socket or a streaming [IPC][] endpoint 398(uses named pipes on Windows, and Unix domain sockets otherwise). It is also 399an [`EventEmitter`][]. 400 401A `net.Socket` can be created by the user and used directly to interact with 402a server. For example, it is returned by [`net.createConnection()`][], 403so the user can use it to talk to the server. 404 405It can also be created by Node.js and passed to the user when a connection 406is received. For example, it is passed to the listeners of a 407[`'connection'`][] event emitted on a [`net.Server`][], so the user can use 408it to interact with the client. 409 410### `new net.Socket([options])` 411<!-- YAML 412added: v0.3.4 413--> 414 415* `options` {Object} Available options are: 416 * `fd` {number} If specified, wrap around an existing socket with 417 the given file descriptor, otherwise a new socket will be created. 418 * `allowHalfOpen` {boolean} Indicates whether half-opened TCP connections 419 are allowed. See [`net.createServer()`][] and the [`'end'`][] event 420 for details. **Default:** `false`. 421 * `readable` {boolean} Allow reads on the socket when an `fd` is passed, 422 otherwise ignored. **Default:** `false`. 423 * `writable` {boolean} Allow writes on the socket when an `fd` is passed, 424 otherwise ignored. **Default:** `false`. 425* Returns: {net.Socket} 426 427Creates a new socket object. 428 429The newly created socket can be either a TCP socket or a streaming [IPC][] 430endpoint, depending on what it [`connect()`][`socket.connect()`] to. 431 432### Event: `'close'` 433<!-- YAML 434added: v0.1.90 435--> 436 437* `hadError` {boolean} `true` if the socket had a transmission error. 438 439Emitted once the socket is fully closed. The argument `hadError` is a boolean 440which says if the socket was closed due to a transmission error. 441 442### Event: `'connect'` 443<!-- YAML 444added: v0.1.90 445--> 446 447Emitted when a socket connection is successfully established. 448See [`net.createConnection()`][]. 449 450### Event: `'data'` 451<!-- YAML 452added: v0.1.90 453--> 454 455* {Buffer|string} 456 457Emitted when data is received. The argument `data` will be a `Buffer` or 458`String`. Encoding of data is set by [`socket.setEncoding()`][]. 459 460The data will be lost if there is no listener when a `Socket` 461emits a `'data'` event. 462 463### Event: `'drain'` 464<!-- YAML 465added: v0.1.90 466--> 467 468Emitted when the write buffer becomes empty. Can be used to throttle uploads. 469 470See also: the return values of `socket.write()`. 471 472### Event: `'end'` 473<!-- YAML 474added: v0.1.90 475--> 476 477Emitted when the other end of the socket sends a FIN packet, thus ending the 478readable side of the socket. 479 480By default (`allowHalfOpen` is `false`) the socket will send a FIN packet 481back and destroy its file descriptor once it has written out its pending 482write queue. However, if `allowHalfOpen` is set to `true`, the socket will 483not automatically [`end()`][`socket.end()`] its writable side, allowing the 484user to write arbitrary amounts of data. The user must call 485[`end()`][`socket.end()`] explicitly to close the connection (i.e. sending a 486FIN packet back). 487 488### Event: `'error'` 489<!-- YAML 490added: v0.1.90 491--> 492 493* {Error} 494 495Emitted when an error occurs. The `'close'` event will be called directly 496following this event. 497 498### Event: `'lookup'` 499<!-- YAML 500added: v0.11.3 501changes: 502 - version: v5.10.0 503 pr-url: https://github.com/nodejs/node/pull/5598 504 description: The `host` parameter is supported now. 505--> 506 507Emitted after resolving the host name but before connecting. 508Not applicable to Unix sockets. 509 510* `err` {Error|null} The error object. See [`dns.lookup()`][]. 511* `address` {string} The IP address. 512* `family` {string|null} The address type. See [`dns.lookup()`][]. 513* `host` {string} The host name. 514 515### Event: `'ready'` 516<!-- YAML 517added: v9.11.0 518--> 519 520Emitted when a socket is ready to be used. 521 522Triggered immediately after `'connect'`. 523 524### Event: `'timeout'` 525<!-- YAML 526added: v0.1.90 527--> 528 529Emitted if the socket times out from inactivity. This is only to notify that 530the socket has been idle. The user must manually close the connection. 531 532See also: [`socket.setTimeout()`][]. 533 534### `socket.address()` 535<!-- YAML 536added: v0.1.90 537--> 538 539* Returns: {Object} 540 541Returns the bound `address`, the address `family` name and `port` of the 542socket as reported by the operating system: 543`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` 544 545### `socket.bufferSize` 546<!-- YAML 547added: v0.3.8 548--> 549 550* {integer} 551 552This property shows the number of characters buffered for writing. The buffer 553may contain strings whose length after encoding is not yet known. So this number 554is only an approximation of the number of bytes in the buffer. 555 556`net.Socket` has the property that `socket.write()` always works. This is to 557help users get up and running quickly. The computer cannot always keep up 558with the amount of data that is written to a socket. The network connection 559simply might be too slow. Node.js will internally queue up the data written to a 560socket and send it out over the wire when it is possible. 561 562The consequence of this internal buffering is that memory may grow. 563Users who experience large or growing `bufferSize` should attempt to 564"throttle" the data flows in their program with 565[`socket.pause()`][] and [`socket.resume()`][]. 566 567### `socket.bytesRead` 568<!-- YAML 569added: v0.5.3 570--> 571 572* {integer} 573 574The amount of received bytes. 575 576### `socket.bytesWritten` 577<!-- YAML 578added: v0.5.3 579--> 580 581* {integer} 582 583The amount of bytes sent. 584 585### `socket.connect()` 586 587Initiate a connection on a given socket. 588 589Possible signatures: 590 591* [`socket.connect(options[, connectListener])`][`socket.connect(options)`] 592* [`socket.connect(path[, connectListener])`][`socket.connect(path)`] 593 for [IPC][] connections. 594* [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`] 595 for TCP connections. 596* Returns: {net.Socket} The socket itself. 597 598This function is asynchronous. When the connection is established, the 599[`'connect'`][] event will be emitted. If there is a problem connecting, 600instead of a [`'connect'`][] event, an [`'error'`][] event will be emitted with 601the error passed to the [`'error'`][] listener. 602The last parameter `connectListener`, if supplied, will be added as a listener 603for the [`'connect'`][] event **once**. 604 605This function should only be used for reconnecting a socket after 606`'close'` has been emitted or otherwise it may lead to undefined 607behavior. 608 609#### `socket.connect(options[, connectListener])` 610<!-- YAML 611added: v0.1.90 612changes: 613 - version: v12.10.0 614 pr-url: https://github.com/nodejs/node/pull/25436 615 description: Added `onread` option. 616 - version: v6.0.0 617 pr-url: https://github.com/nodejs/node/pull/6021 618 description: The `hints` option defaults to `0` in all cases now. 619 Previously, in the absence of the `family` option it would 620 default to `dns.ADDRCONFIG | dns.V4MAPPED`. 621 - version: v5.11.0 622 pr-url: https://github.com/nodejs/node/pull/6000 623 description: The `hints` option is supported now. 624--> 625 626* `options` {Object} 627* `connectListener` {Function} Common parameter of [`socket.connect()`][] 628 methods. Will be added as a listener for the [`'connect'`][] event once. 629* Returns: {net.Socket} The socket itself. 630 631Initiate a connection on a given socket. Normally this method is not needed, 632the socket should be created and opened with [`net.createConnection()`][]. Use 633this only when implementing a custom Socket. 634 635For TCP connections, available `options` are: 636 637* `port` {number} Required. Port the socket should connect to. 638* `host` {string} Host the socket should connect to. **Default:** `'localhost'`. 639* `localAddress` {string} Local address the socket should connect from. 640* `localPort` {number} Local port the socket should connect from. 641* `family` {number}: Version of IP stack. Must be `4`, `6`, or `0`. The value 642 `0` indicates that both IPv4 and IPv6 addresses are allowed. **Default:** `0`. 643* `hints` {number} Optional [`dns.lookup()` hints][]. 644* `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][]. 645 646For [IPC][] connections, available `options` are: 647 648* `path` {string} Required. Path the client should connect to. 649 See [Identifying paths for IPC connections][]. If provided, the TCP-specific 650 options above are ignored. 651 652For both types, available `options` include: 653 654* `onread` {Object} If specified, incoming data is stored in a single `buffer` 655 and passed to the supplied `callback` when data arrives on the socket. 656 This will cause the streaming functionality to not provide any data. 657 The socket will emit events like `'error'`, `'end'`, and `'close'` 658 as usual. Methods like `pause()` and `resume()` will also behave as 659 expected. 660 * `buffer` {Buffer|Uint8Array|Function} Either a reusable chunk of memory to 661 use for storing incoming data or a function that returns such. 662 * `callback` {Function} This function is called for every chunk of incoming 663 data. Two arguments are passed to it: the number of bytes written to 664 `buffer` and a reference to `buffer`. Return `false` from this function to 665 implicitly `pause()` the socket. This function will be executed in the 666 global context. 667 668Following is an example of a client using the `onread` option: 669 670```js 671const net = require('net'); 672net.connect({ 673 port: 80, 674 onread: { 675 // Reuses a 4KiB Buffer for every read from the socket. 676 buffer: Buffer.alloc(4 * 1024), 677 callback: function(nread, buf) { 678 // Received data is available in `buf` from 0 to `nread`. 679 console.log(buf.toString('utf8', 0, nread)); 680 } 681 } 682}); 683``` 684 685#### `socket.connect(path[, connectListener])` 686 687* `path` {string} Path the client should connect to. See 688 [Identifying paths for IPC connections][]. 689* `connectListener` {Function} Common parameter of [`socket.connect()`][] 690 methods. Will be added as a listener for the [`'connect'`][] event once. 691* Returns: {net.Socket} The socket itself. 692 693Initiate an [IPC][] connection on the given socket. 694 695Alias to 696[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 697called with `{ path: path }` as `options`. 698 699#### `socket.connect(port[, host][, connectListener])` 700<!-- YAML 701added: v0.1.90 702--> 703 704* `port` {number} Port the client should connect to. 705* `host` {string} Host the client should connect to. 706* `connectListener` {Function} Common parameter of [`socket.connect()`][] 707 methods. Will be added as a listener for the [`'connect'`][] event once. 708* Returns: {net.Socket} The socket itself. 709 710Initiate a TCP connection on the given socket. 711 712Alias to 713[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 714called with `{port: port, host: host}` as `options`. 715 716### `socket.connecting` 717<!-- YAML 718added: v6.1.0 719--> 720 721* {boolean} 722 723If `true`, 724[`socket.connect(options[, connectListener])`][`socket.connect(options)`] was 725called and has not yet finished. It will stay `true` until the socket becomes 726connected, then it is set to `false` and the `'connect'` event is emitted. Note 727that the 728[`socket.connect(options[, connectListener])`][`socket.connect(options)`] 729callback is a listener for the `'connect'` event. 730 731### `socket.destroy([error])` 732<!-- YAML 733added: v0.1.90 734--> 735 736* `error` {Object} 737* Returns: {net.Socket} 738 739Ensures that no more I/O activity happens on this socket. 740Destroys the stream and closes the connection. 741 742See [`writable.destroy()`][] for further details. 743 744### `socket.destroyed` 745 746* {boolean} Indicates if the connection is destroyed or not. Once a 747 connection is destroyed no further data can be transferred using it. 748 749See [`writable.destroyed`][] for further details. 750 751### `socket.end([data[, encoding]][, callback])` 752<!-- YAML 753added: v0.1.90 754--> 755 756* `data` {string|Buffer|Uint8Array} 757* `encoding` {string} Only used when data is `string`. **Default:** `'utf8'`. 758* `callback` {Function} Optional callback for when the socket is finished. 759* Returns: {net.Socket} The socket itself. 760 761Half-closes the socket. i.e., it sends a FIN packet. It is possible the 762server will still send some data. 763 764See [`writable.end()`][] for further details. 765 766### `socket.localAddress` 767<!-- YAML 768added: v0.9.6 769--> 770 771* {string} 772 773The string representation of the local IP address the remote client is 774connecting on. For example, in a server listening on `'0.0.0.0'`, if a client 775connects on `'192.168.1.1'`, the value of `socket.localAddress` would be 776`'192.168.1.1'`. 777 778### `socket.localPort` 779<!-- YAML 780added: v0.9.6 781--> 782 783* {integer} 784 785The numeric representation of the local port. For example, `80` or `21`. 786 787### `socket.pause()` 788 789* Returns: {net.Socket} The socket itself. 790 791Pauses the reading of data. That is, [`'data'`][] events will not be emitted. 792Useful to throttle back an upload. 793 794### `socket.pending` 795<!-- YAML 796added: v11.2.0 797--> 798 799* {boolean} 800 801This is `true` if the socket is not connected yet, either because `.connect()` 802has not yet been called or because it is still in the process of connecting 803(see [`socket.connecting`][]). 804 805### `socket.ref()` 806<!-- YAML 807added: v0.9.1 808--> 809 810* Returns: {net.Socket} The socket itself. 811 812Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will 813*not* let the program exit if it's the only socket left (the default behavior). 814If the socket is `ref`ed calling `ref` again will have no effect. 815 816### `socket.remoteAddress` 817<!-- YAML 818added: v0.5.10 819--> 820 821* {string} 822 823The string representation of the remote IP address. For example, 824`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if 825the socket is destroyed (for example, if the client disconnected). 826 827### `socket.remoteFamily` 828<!-- YAML 829added: v0.11.14 830--> 831 832* {string} 833 834The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. 835 836### `socket.remotePort` 837<!-- YAML 838added: v0.5.10 839--> 840 841* {integer} 842 843The numeric representation of the remote port. For example, `80` or `21`. 844 845### `socket.resume()` 846 847* Returns: {net.Socket} The socket itself. 848 849Resumes reading after a call to [`socket.pause()`][]. 850 851### `socket.setEncoding([encoding])` 852<!-- YAML 853added: v0.1.90 854--> 855 856* `encoding` {string} 857* Returns: {net.Socket} The socket itself. 858 859Set the encoding for the socket as a [Readable Stream][]. See 860[`readable.setEncoding()`][] for more information. 861 862### `socket.setKeepAlive([enable][, initialDelay])` 863<!-- YAML 864added: v0.1.92 865--> 866 867* `enable` {boolean} **Default:** `false` 868* `initialDelay` {number} **Default:** `0` 869* Returns: {net.Socket} The socket itself. 870 871Enable/disable keep-alive functionality, and optionally set the initial 872delay before the first keepalive probe is sent on an idle socket. 873 874Set `initialDelay` (in milliseconds) to set the delay between the last 875data packet received and the first keepalive probe. Setting `0` for 876`initialDelay` will leave the value unchanged from the default 877(or previous) setting. 878 879### `socket.setNoDelay([noDelay])` 880<!-- YAML 881added: v0.1.90 882--> 883 884* `noDelay` {boolean} **Default:** `true` 885* Returns: {net.Socket} The socket itself. 886 887Enable/disable the use of Nagle's algorithm. 888 889When a TCP connection is created, it will have Nagle's algorithm enabled. 890 891Nagle's algorithm delays data before it is sent via the network. It attempts 892to optimize throughput at the expense of latency. 893 894Passing `true` for `noDelay` or not passing an argument will disable Nagle's 895algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's 896algorithm. 897 898### `socket.setTimeout(timeout[, callback])` 899<!-- YAML 900added: v0.1.90 901--> 902 903* `timeout` {number} 904* `callback` {Function} 905* Returns: {net.Socket} The socket itself. 906 907Sets the socket to timeout after `timeout` milliseconds of inactivity on 908the socket. By default `net.Socket` do not have a timeout. 909 910When an idle timeout is triggered the socket will receive a [`'timeout'`][] 911event but the connection will not be severed. The user must manually call 912[`socket.end()`][] or [`socket.destroy()`][] to end the connection. 913 914```js 915socket.setTimeout(3000); 916socket.on('timeout', () => { 917 console.log('socket timeout'); 918 socket.end(); 919}); 920``` 921 922If `timeout` is 0, then the existing idle timeout is disabled. 923 924The optional `callback` parameter will be added as a one-time listener for the 925[`'timeout'`][] event. 926 927### `socket.unref()` 928<!-- YAML 929added: v0.9.1 930--> 931 932* Returns: {net.Socket} The socket itself. 933 934Calling `unref()` on a socket will allow the program to exit if this is the only 935active socket in the event system. If the socket is already `unref`ed calling 936`unref()` again will have no effect. 937 938### `socket.write(data[, encoding][, callback])` 939<!-- YAML 940added: v0.1.90 941--> 942 943* `data` {string|Buffer|Uint8Array} 944* `encoding` {string} Only used when data is `string`. **Default:** `utf8`. 945* `callback` {Function} 946* Returns: {boolean} 947 948Sends data on the socket. The second parameter specifies the encoding in the 949case of a string. It defaults to UTF8 encoding. 950 951Returns `true` if the entire data was flushed successfully to the kernel 952buffer. Returns `false` if all or part of the data was queued in user memory. 953[`'drain'`][] will be emitted when the buffer is again free. 954 955The optional `callback` parameter will be executed when the data is finally 956written out, which may not be immediately. 957 958See `Writable` stream [`write()`][stream_writable_write] method for more 959information. 960 961## `net.connect()` 962 963Aliases to 964[`net.createConnection()`][`net.createConnection()`]. 965 966Possible signatures: 967 968* [`net.connect(options[, connectListener])`][`net.connect(options)`] 969* [`net.connect(path[, connectListener])`][`net.connect(path)`] for [IPC][] 970 connections. 971* [`net.connect(port[, host][, connectListener])`][`net.connect(port, host)`] 972 for TCP connections. 973 974### `net.connect(options[, connectListener])` 975<!-- YAML 976added: v0.7.0 977--> 978 979* `options` {Object} 980* `connectListener` {Function} 981* Returns: {net.Socket} 982 983Alias to 984[`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. 985 986### `net.connect(path[, connectListener])` 987<!-- YAML 988added: v0.1.90 989--> 990 991* `path` {string} 992* `connectListener` {Function} 993* Returns: {net.Socket} 994 995Alias to 996[`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]. 997 998### `net.connect(port[, host][, connectListener])` 999<!-- YAML 1000added: v0.1.90 1001--> 1002 1003* `port` {number} 1004* `host` {string} 1005* `connectListener` {Function} 1006* Returns: {net.Socket} 1007 1008Alias to 1009[`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`]. 1010 1011## `net.createConnection()` 1012 1013A factory function, which creates a new [`net.Socket`][], 1014immediately initiates connection with [`socket.connect()`][], 1015then returns the `net.Socket` that starts the connection. 1016 1017When the connection is established, a [`'connect'`][] event will be emitted 1018on the returned socket. The last parameter `connectListener`, if supplied, 1019will be added as a listener for the [`'connect'`][] event **once**. 1020 1021Possible signatures: 1022 1023* [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`] 1024* [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`] 1025 for [IPC][] connections. 1026* [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`] 1027 for TCP connections. 1028 1029The [`net.connect()`][] function is an alias to this function. 1030 1031### `net.createConnection(options[, connectListener])` 1032<!-- YAML 1033added: v0.1.90 1034--> 1035 1036* `options` {Object} Required. Will be passed to both the 1037 [`new net.Socket([options])`][`new net.Socket(options)`] call and the 1038 [`socket.connect(options[, connectListener])`][`socket.connect(options)`] 1039 method. 1040* `connectListener` {Function} Common parameter of the 1041 [`net.createConnection()`][] functions. If supplied, will be added as 1042 a listener for the [`'connect'`][] event on the returned socket once. 1043* Returns: {net.Socket} The newly created socket used to start the connection. 1044 1045For available options, see 1046[`new net.Socket([options])`][`new net.Socket(options)`] 1047and [`socket.connect(options[, connectListener])`][`socket.connect(options)`]. 1048 1049Additional options: 1050 1051* `timeout` {number} If set, will be used to call 1052 [`socket.setTimeout(timeout)`][] after the socket is created, but before 1053 it starts the connection. 1054 1055Following is an example of a client of the echo server described 1056in the [`net.createServer()`][] section: 1057 1058```js 1059const net = require('net'); 1060const client = net.createConnection({ port: 8124 }, () => { 1061 // 'connect' listener. 1062 console.log('connected to server!'); 1063 client.write('world!\r\n'); 1064}); 1065client.on('data', (data) => { 1066 console.log(data.toString()); 1067 client.end(); 1068}); 1069client.on('end', () => { 1070 console.log('disconnected from server'); 1071}); 1072``` 1073 1074To connect on the socket `/tmp/echo.sock`: 1075 1076```js 1077const client = net.createConnection({ path: '/tmp/echo.sock' }); 1078``` 1079 1080### `net.createConnection(path[, connectListener])` 1081<!-- YAML 1082added: v0.1.90 1083--> 1084 1085* `path` {string} Path the socket should connect to. Will be passed to 1086 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 1087 See [Identifying paths for IPC connections][]. 1088* `connectListener` {Function} Common parameter of the 1089 [`net.createConnection()`][] functions, an "once" listener for the 1090 `'connect'` event on the initiating socket. Will be passed to 1091 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 1092* Returns: {net.Socket} The newly created socket used to start the connection. 1093 1094Initiates an [IPC][] connection. 1095 1096This function creates a new [`net.Socket`][] with all options set to default, 1097immediately initiates connection with 1098[`socket.connect(path[, connectListener])`][`socket.connect(path)`], 1099then returns the `net.Socket` that starts the connection. 1100 1101### `net.createConnection(port[, host][, connectListener])` 1102<!-- YAML 1103added: v0.1.90 1104--> 1105 1106* `port` {number} Port the socket should connect to. Will be passed to 1107 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1108* `host` {string} Host the socket should connect to. Will be passed to 1109 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1110 **Default:** `'localhost'`. 1111* `connectListener` {Function} Common parameter of the 1112 [`net.createConnection()`][] functions, an "once" listener for the 1113 `'connect'` event on the initiating socket. Will be passed to 1114 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. 1115* Returns: {net.Socket} The newly created socket used to start the connection. 1116 1117Initiates a TCP connection. 1118 1119This function creates a new [`net.Socket`][] with all options set to default, 1120immediately initiates connection with 1121[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`], 1122then returns the `net.Socket` that starts the connection. 1123 1124## `net.createServer([options][, connectionListener])` 1125<!-- YAML 1126added: v0.5.0 1127--> 1128 1129* `options` {Object} 1130 * `allowHalfOpen` {boolean} Indicates whether half-opened TCP 1131 connections are allowed. **Default:** `false`. 1132 * `pauseOnConnect` {boolean} Indicates whether the socket should be 1133 paused on incoming connections. **Default:** `false`. 1134* `connectionListener` {Function} Automatically set as a listener for the 1135 [`'connection'`][] event. 1136* Returns: {net.Server} 1137 1138Creates a new TCP or [IPC][] server. 1139 1140If `allowHalfOpen` is set to `true`, when the other end of the socket 1141sends a FIN packet, the server will only send a FIN packet back when 1142[`socket.end()`][] is explicitly called, until then the connection is 1143half-closed (non-readable but still writable). See [`'end'`][] event 1144and [RFC 1122][half-closed] (section 4.2.2.13) for more information. 1145 1146If `pauseOnConnect` is set to `true`, then the socket associated with each 1147incoming connection will be paused, and no data will be read from its handle. 1148This allows connections to be passed between processes without any data being 1149read by the original process. To begin reading data from a paused socket, call 1150[`socket.resume()`][]. 1151 1152The server can be a TCP server or an [IPC][] server, depending on what it 1153[`listen()`][`server.listen()`] to. 1154 1155Here is an example of an TCP echo server which listens for connections 1156on port 8124: 1157 1158```js 1159const net = require('net'); 1160const server = net.createServer((c) => { 1161 // 'connection' listener. 1162 console.log('client connected'); 1163 c.on('end', () => { 1164 console.log('client disconnected'); 1165 }); 1166 c.write('hello\r\n'); 1167 c.pipe(c); 1168}); 1169server.on('error', (err) => { 1170 throw err; 1171}); 1172server.listen(8124, () => { 1173 console.log('server bound'); 1174}); 1175``` 1176 1177Test this by using `telnet`: 1178 1179```console 1180$ telnet localhost 8124 1181``` 1182 1183To listen on the socket `/tmp/echo.sock`: 1184 1185```js 1186server.listen('/tmp/echo.sock', () => { 1187 console.log('server bound'); 1188}); 1189``` 1190 1191Use `nc` to connect to a Unix domain socket server: 1192 1193```console 1194$ nc -U /tmp/echo.sock 1195``` 1196 1197## `net.isIP(input)` 1198<!-- YAML 1199added: v0.3.0 1200--> 1201 1202* `input` {string} 1203* Returns: {integer} 1204 1205Tests if input is an IP address. Returns `0` for invalid strings, 1206returns `4` for IP version 4 addresses, and returns `6` for IP version 6 1207addresses. 1208 1209## `net.isIPv4(input)` 1210<!-- YAML 1211added: v0.3.0 1212--> 1213 1214* `input` {string} 1215* Returns: {boolean} 1216 1217Returns `true` if input is a version 4 IP address, otherwise returns `false`. 1218 1219## `net.isIPv6(input)` 1220<!-- YAML 1221added: v0.3.0 1222--> 1223 1224* `input` {string} 1225* Returns: {boolean} 1226 1227Returns `true` if input is a version 6 IP address, otherwise returns `false`. 1228 1229[IPC]: #net_ipc_support 1230[Identifying paths for IPC connections]: #net_identifying_paths_for_ipc_connections 1231[Readable Stream]: stream.html#stream_class_stream_readable 1232[`'close'`]: #net_event_close 1233[`'connect'`]: #net_event_connect 1234[`'connection'`]: #net_event_connection 1235[`'data'`]: #net_event_data 1236[`'drain'`]: #net_event_drain 1237[`'end'`]: #net_event_end 1238[`'error'`]: #net_event_error_1 1239[`'listening'`]: #net_event_listening 1240[`'timeout'`]: #net_event_timeout 1241[`EventEmitter`]: events.html#events_class_eventemitter 1242[`child_process.fork()`]: child_process.html#child_process_child_process_fork_modulepath_args_options 1243[`dns.lookup()` hints]: dns.html#dns_supported_getaddrinfo_flags 1244[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback 1245[`net.Server`]: #net_class_net_server 1246[`net.Socket`]: #net_class_net_socket 1247[`net.connect()`]: #net_net_connect 1248[`net.connect(options)`]: #net_net_connect_options_connectlistener 1249[`net.connect(path)`]: #net_net_connect_path_connectlistener 1250[`net.connect(port, host)`]: #net_net_connect_port_host_connectlistener 1251[`net.createConnection()`]: #net_net_createconnection 1252[`net.createConnection(options)`]: #net_net_createconnection_options_connectlistener 1253[`net.createConnection(path)`]: #net_net_createconnection_path_connectlistener 1254[`net.createConnection(port, host)`]: #net_net_createconnection_port_host_connectlistener 1255[`net.createServer()`]: #net_net_createserver_options_connectionlistener 1256[`new net.Socket(options)`]: #net_new_net_socket_options 1257[`readable.setEncoding()`]: stream.html#stream_readable_setencoding_encoding 1258[`server.close()`]: #net_server_close_callback 1259[`server.getConnections()`]: #net_server_getconnections_callback 1260[`server.listen()`]: #net_server_listen 1261[`server.listen(handle)`]: #net_server_listen_handle_backlog_callback 1262[`server.listen(options)`]: #net_server_listen_options_callback 1263[`server.listen(path)`]: #net_server_listen_path_backlog_callback 1264[`socket(7)`]: https://man7.org/linux/man-pages/man7/socket.7.html 1265[`socket.connect()`]: #net_socket_connect 1266[`socket.connect(options)`]: #net_socket_connect_options_connectlistener 1267[`socket.connect(path)`]: #net_socket_connect_path_connectlistener 1268[`socket.connect(port)`]: #net_socket_connect_port_host_connectlistener 1269[`socket.connecting`]: #net_socket_connecting 1270[`socket.destroy()`]: #net_socket_destroy_error 1271[`socket.end()`]: #net_socket_end_data_encoding_callback 1272[`socket.pause()`]: #net_socket_pause 1273[`socket.resume()`]: #net_socket_resume 1274[`socket.setEncoding()`]: #net_socket_setencoding_encoding 1275[`socket.setTimeout()`]: #net_socket_settimeout_timeout_callback 1276[`socket.setTimeout(timeout)`]: #net_socket_settimeout_timeout_callback 1277[`writable.destroyed`]: stream.html#stream_writable_destroyed 1278[`writable.destroy()`]: stream.html#stream_writable_destroy_error 1279[`writable.end()`]: stream.html#stream_writable_end_chunk_encoding_callback 1280[half-closed]: https://tools.ietf.org/html/rfc1122 1281[stream_writable_write]: stream.html#stream_writable_write_chunk_encoding_callback 1282[unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0 1283[unspecified IPv6 address]: https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address 1284