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