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