f7270a377941439672022703311bd3a273e791a1b980c002544e1ee02a8d4eaedf07befbdc43923f57487fd3baeb588d423395b92e3baf312cb35e5fbd3d67 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. /**
  2. * > Stability: 2 - Stable
  3. *
  4. * The `node:net` module provides an asynchronous network API for creating stream-based
  5. * TCP or `IPC` servers ({@link createServer}) and clients
  6. * ({@link createConnection}).
  7. *
  8. * It can be accessed using:
  9. *
  10. * ```js
  11. * import net from 'node:net';
  12. * ```
  13. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js)
  14. */
  15. declare module "net" {
  16. import * as stream from "node:stream";
  17. import { Abortable, EventEmitter } from "node:events";
  18. import * as dns from "node:dns";
  19. type LookupFunction = (
  20. hostname: string,
  21. options: dns.LookupOptions,
  22. callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void,
  23. ) => void;
  24. interface AddressInfo {
  25. address: string;
  26. family: string;
  27. port: number;
  28. }
  29. interface SocketConstructorOpts {
  30. fd?: number | undefined;
  31. allowHalfOpen?: boolean | undefined;
  32. onread?: OnReadOpts | undefined;
  33. readable?: boolean | undefined;
  34. writable?: boolean | undefined;
  35. signal?: AbortSignal;
  36. }
  37. interface OnReadOpts {
  38. buffer: Uint8Array | (() => Uint8Array);
  39. /**
  40. * This function is called for every chunk of incoming data.
  41. * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`.
  42. * Return `false` from this function to implicitly `pause()` the socket.
  43. */
  44. callback(bytesWritten: number, buffer: Uint8Array): boolean;
  45. }
  46. // TODO: remove empty ConnectOpts placeholder at next major @types/node version.
  47. /** @deprecated */
  48. interface ConnectOpts {}
  49. interface TcpSocketConnectOpts {
  50. port: number;
  51. host?: string | undefined;
  52. localAddress?: string | undefined;
  53. localPort?: number | undefined;
  54. hints?: number | undefined;
  55. family?: number | undefined;
  56. lookup?: LookupFunction | undefined;
  57. noDelay?: boolean | undefined;
  58. keepAlive?: boolean | undefined;
  59. keepAliveInitialDelay?: number | undefined;
  60. /**
  61. * @since v18.13.0
  62. */
  63. autoSelectFamily?: boolean | undefined;
  64. /**
  65. * @since v18.13.0
  66. */
  67. autoSelectFamilyAttemptTimeout?: number | undefined;
  68. blockList?: BlockList | undefined;
  69. }
  70. interface IpcSocketConnectOpts {
  71. path: string;
  72. }
  73. type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
  74. type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed";
  75. /**
  76. * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint
  77. * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also
  78. * an `EventEmitter`.
  79. *
  80. * A `net.Socket` can be created by the user and used directly to interact with
  81. * a server. For example, it is returned by {@link createConnection},
  82. * so the user can use it to talk to the server.
  83. *
  84. * It can also be created by Node.js and passed to the user when a connection
  85. * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use
  86. * it to interact with the client.
  87. * @since v0.3.4
  88. */
  89. class Socket extends stream.Duplex {
  90. constructor(options?: SocketConstructorOpts);
  91. /**
  92. * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately.
  93. * If the socket is still writable it implicitly calls `socket.end()`.
  94. * @since v0.3.4
  95. */
  96. destroySoon(): void;
  97. /**
  98. * Sends data on the socket. The second parameter specifies the encoding in the
  99. * case of a string. It defaults to UTF8 encoding.
  100. *
  101. * Returns `true` if the entire data was flushed successfully to the kernel
  102. * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free.
  103. *
  104. * The optional `callback` parameter will be executed when the data is finally
  105. * written out, which may not be immediately.
  106. *
  107. * See `Writable` stream `write()` method for more
  108. * information.
  109. * @since v0.1.90
  110. * @param [encoding='utf8'] Only used when data is `string`.
  111. */
  112. write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
  113. write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean;
  114. /**
  115. * Initiate a connection on a given socket.
  116. *
  117. * Possible signatures:
  118. *
  119. * * `socket.connect(options[, connectListener])`
  120. * * `socket.connect(path[, connectListener])` for `IPC` connections.
  121. * * `socket.connect(port[, host][, connectListener])` for TCP connections.
  122. * * Returns: `net.Socket` The socket itself.
  123. *
  124. * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting,
  125. * instead of a `'connect'` event, an `'error'` event will be emitted with
  126. * the error passed to the `'error'` listener.
  127. * The last parameter `connectListener`, if supplied, will be added as a listener
  128. * for the `'connect'` event **once**.
  129. *
  130. * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined
  131. * behavior.
  132. */
  133. connect(options: SocketConnectOpts, connectionListener?: () => void): this;
  134. connect(port: number, host: string, connectionListener?: () => void): this;
  135. connect(port: number, connectionListener?: () => void): this;
  136. connect(path: string, connectionListener?: () => void): this;
  137. /**
  138. * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information.
  139. * @since v0.1.90
  140. * @return The socket itself.
  141. */
  142. setEncoding(encoding?: BufferEncoding): this;
  143. /**
  144. * Pauses the reading of data. That is, `'data'` events will not be emitted.
  145. * Useful to throttle back an upload.
  146. * @return The socket itself.
  147. */
  148. pause(): this;
  149. /**
  150. * Close the TCP connection by sending an RST packet and destroy the stream.
  151. * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
  152. * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error.
  153. * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error.
  154. * @since v18.3.0, v16.17.0
  155. */
  156. resetAndDestroy(): this;
  157. /**
  158. * Resumes reading after a call to `socket.pause()`.
  159. * @return The socket itself.
  160. */
  161. resume(): this;
  162. /**
  163. * Sets the socket to timeout after `timeout` milliseconds of inactivity on
  164. * the socket. By default `net.Socket` do not have a timeout.
  165. *
  166. * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to
  167. * end the connection.
  168. *
  169. * ```js
  170. * socket.setTimeout(3000);
  171. * socket.on('timeout', () => {
  172. * console.log('socket timeout');
  173. * socket.end();
  174. * });
  175. * ```
  176. *
  177. * If `timeout` is 0, then the existing idle timeout is disabled.
  178. *
  179. * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event.
  180. * @since v0.1.90
  181. * @return The socket itself.
  182. */
  183. setTimeout(timeout: number, callback?: () => void): this;
  184. /**
  185. * Enable/disable the use of Nagle's algorithm.
  186. *
  187. * When a TCP connection is created, it will have Nagle's algorithm enabled.
  188. *
  189. * Nagle's algorithm delays data before it is sent via the network. It attempts
  190. * to optimize throughput at the expense of latency.
  191. *
  192. * Passing `true` for `noDelay` or not passing an argument will disable Nagle's
  193. * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's
  194. * algorithm.
  195. * @since v0.1.90
  196. * @param [noDelay=true]
  197. * @return The socket itself.
  198. */
  199. setNoDelay(noDelay?: boolean): this;
  200. /**
  201. * Enable/disable keep-alive functionality, and optionally set the initial
  202. * delay before the first keepalive probe is sent on an idle socket.
  203. *
  204. * Set `initialDelay` (in milliseconds) to set the delay between the last
  205. * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default
  206. * (or previous) setting.
  207. *
  208. * Enabling the keep-alive functionality will set the following socket options:
  209. *
  210. * * `SO_KEEPALIVE=1`
  211. * * `TCP_KEEPIDLE=initialDelay`
  212. * * `TCP_KEEPCNT=10`
  213. * * `TCP_KEEPINTVL=1`
  214. * @since v0.1.92
  215. * @param [enable=false]
  216. * @param [initialDelay=0]
  217. * @return The socket itself.
  218. */
  219. setKeepAlive(enable?: boolean, initialDelay?: number): this;
  220. /**
  221. * Returns the bound `address`, the address `family` name and `port` of the
  222. * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
  223. * @since v0.1.90
  224. */
  225. address(): AddressInfo | {};
  226. /**
  227. * Calling `unref()` on a socket will allow the program to exit if this is the only
  228. * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect.
  229. * @since v0.9.1
  230. * @return The socket itself.
  231. */
  232. unref(): this;
  233. /**
  234. * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior).
  235. * If the socket is `ref`ed calling `ref` again will have no effect.
  236. * @since v0.9.1
  237. * @return The socket itself.
  238. */
  239. ref(): this;
  240. /**
  241. * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)`
  242. * and it is an array of the addresses that have been attempted.
  243. *
  244. * Each address is a string in the form of `$IP:$PORT`.
  245. * If the connection was successful, then the last address is the one that the socket is currently connected to.
  246. * @since v19.4.0
  247. */
  248. readonly autoSelectFamilyAttemptedAddresses: string[];
  249. /**
  250. * This property shows the number of characters buffered for writing. The buffer
  251. * may contain strings whose length after encoding is not yet known. So this number
  252. * is only an approximation of the number of bytes in the buffer.
  253. *
  254. * `net.Socket` has the property that `socket.write()` always works. This is to
  255. * help users get up and running quickly. The computer cannot always keep up
  256. * with the amount of data that is written to a socket. The network connection
  257. * simply might be too slow. Node.js will internally queue up the data written to a
  258. * socket and send it out over the wire when it is possible.
  259. *
  260. * The consequence of this internal buffering is that memory may grow.
  261. * Users who experience large or growing `bufferSize` should attempt to
  262. * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`.
  263. * @since v0.3.8
  264. * @deprecated Since v14.6.0 - Use `writableLength` instead.
  265. */
  266. readonly bufferSize: number;
  267. /**
  268. * The amount of received bytes.
  269. * @since v0.5.3
  270. */
  271. readonly bytesRead: number;
  272. /**
  273. * The amount of bytes sent.
  274. * @since v0.5.3
  275. */
  276. readonly bytesWritten: number;
  277. /**
  278. * If `true`, `socket.connect(options[, connectListener])` was
  279. * called and has not yet finished. It will stay `true` until the socket becomes
  280. * connected, then it is set to `false` and the `'connect'` event is emitted. Note
  281. * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event.
  282. * @since v6.1.0
  283. */
  284. readonly connecting: boolean;
  285. /**
  286. * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting
  287. * (see `socket.connecting`).
  288. * @since v11.2.0, v10.16.0
  289. */
  290. readonly pending: boolean;
  291. /**
  292. * See `writable.destroyed` for further details.
  293. */
  294. readonly destroyed: boolean;
  295. /**
  296. * The string representation of the local IP address the remote client is
  297. * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
  298. * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`.
  299. * @since v0.9.6
  300. */
  301. readonly localAddress?: string;
  302. /**
  303. * The numeric representation of the local port. For example, `80` or `21`.
  304. * @since v0.9.6
  305. */
  306. readonly localPort?: number;
  307. /**
  308. * The string representation of the local IP family. `'IPv4'` or `'IPv6'`.
  309. * @since v18.8.0, v16.18.0
  310. */
  311. readonly localFamily?: string;
  312. /**
  313. * This property represents the state of the connection as a string.
  314. *
  315. * * If the stream is connecting `socket.readyState` is `opening`.
  316. * * If the stream is readable and writable, it is `open`.
  317. * * If the stream is readable and not writable, it is `readOnly`.
  318. * * If the stream is not readable and writable, it is `writeOnly`.
  319. * @since v0.5.0
  320. */
  321. readonly readyState: SocketReadyState;
  322. /**
  323. * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if
  324. * the socket is destroyed (for example, if the client disconnected).
  325. * @since v0.5.10
  326. */
  327. readonly remoteAddress?: string | undefined;
  328. /**
  329. * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if
  330. * the socket is destroyed (for example, if the client disconnected).
  331. * @since v0.11.14
  332. */
  333. readonly remoteFamily?: string | undefined;
  334. /**
  335. * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if
  336. * the socket is destroyed (for example, if the client disconnected).
  337. * @since v0.5.10
  338. */
  339. readonly remotePort?: number | undefined;
  340. /**
  341. * The socket timeout in milliseconds as set by `socket.setTimeout()`.
  342. * It is `undefined` if a timeout has not been set.
  343. * @since v10.7.0
  344. */
  345. readonly timeout?: number | undefined;
  346. /**
  347. * Half-closes the socket. i.e., it sends a FIN packet. It is possible the
  348. * server will still send some data.
  349. *
  350. * See `writable.end()` for further details.
  351. * @since v0.1.90
  352. * @param [encoding='utf8'] Only used when data is `string`.
  353. * @param callback Optional callback for when the socket is finished.
  354. * @return The socket itself.
  355. */
  356. end(callback?: () => void): this;
  357. end(buffer: Uint8Array | string, callback?: () => void): this;
  358. end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this;
  359. /**
  360. * events.EventEmitter
  361. * 1. close
  362. * 2. connect
  363. * 3. connectionAttempt
  364. * 4. connectionAttemptFailed
  365. * 5. connectionAttemptTimeout
  366. * 6. data
  367. * 7. drain
  368. * 8. end
  369. * 9. error
  370. * 10. lookup
  371. * 11. ready
  372. * 12. timeout
  373. */
  374. addListener(event: string, listener: (...args: any[]) => void): this;
  375. addListener(event: "close", listener: (hadError: boolean) => void): this;
  376. addListener(event: "connect", listener: () => void): this;
  377. addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  378. addListener(
  379. event: "connectionAttemptFailed",
  380. listener: (ip: string, port: number, family: number, error: Error) => void,
  381. ): this;
  382. addListener(
  383. event: "connectionAttemptTimeout",
  384. listener: (ip: string, port: number, family: number) => void,
  385. ): this;
  386. addListener(event: "data", listener: (data: Buffer) => void): this;
  387. addListener(event: "drain", listener: () => void): this;
  388. addListener(event: "end", listener: () => void): this;
  389. addListener(event: "error", listener: (err: Error) => void): this;
  390. addListener(
  391. event: "lookup",
  392. listener: (err: Error, address: string, family: string | number, host: string) => void,
  393. ): this;
  394. addListener(event: "ready", listener: () => void): this;
  395. addListener(event: "timeout", listener: () => void): this;
  396. emit(event: string | symbol, ...args: any[]): boolean;
  397. emit(event: "close", hadError: boolean): boolean;
  398. emit(event: "connect"): boolean;
  399. emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean;
  400. emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean;
  401. emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean;
  402. emit(event: "data", data: Buffer): boolean;
  403. emit(event: "drain"): boolean;
  404. emit(event: "end"): boolean;
  405. emit(event: "error", err: Error): boolean;
  406. emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean;
  407. emit(event: "ready"): boolean;
  408. emit(event: "timeout"): boolean;
  409. on(event: string, listener: (...args: any[]) => void): this;
  410. on(event: "close", listener: (hadError: boolean) => void): this;
  411. on(event: "connect", listener: () => void): this;
  412. on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  413. on(
  414. event: "connectionAttemptFailed",
  415. listener: (ip: string, port: number, family: number, error: Error) => void,
  416. ): this;
  417. on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
  418. on(event: "data", listener: (data: Buffer) => void): this;
  419. on(event: "drain", listener: () => void): this;
  420. on(event: "end", listener: () => void): this;
  421. on(event: "error", listener: (err: Error) => void): this;
  422. on(
  423. event: "lookup",
  424. listener: (err: Error, address: string, family: string | number, host: string) => void,
  425. ): this;
  426. on(event: "ready", listener: () => void): this;
  427. on(event: "timeout", listener: () => void): this;
  428. once(event: string, listener: (...args: any[]) => void): this;
  429. once(event: "close", listener: (hadError: boolean) => void): this;
  430. once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  431. once(
  432. event: "connectionAttemptFailed",
  433. listener: (ip: string, port: number, family: number, error: Error) => void,
  434. ): this;
  435. once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
  436. once(event: "connect", listener: () => void): this;
  437. once(event: "data", listener: (data: Buffer) => void): this;
  438. once(event: "drain", listener: () => void): this;
  439. once(event: "end", listener: () => void): this;
  440. once(event: "error", listener: (err: Error) => void): this;
  441. once(
  442. event: "lookup",
  443. listener: (err: Error, address: string, family: string | number, host: string) => void,
  444. ): this;
  445. once(event: "ready", listener: () => void): this;
  446. once(event: "timeout", listener: () => void): this;
  447. prependListener(event: string, listener: (...args: any[]) => void): this;
  448. prependListener(event: "close", listener: (hadError: boolean) => void): this;
  449. prependListener(event: "connect", listener: () => void): this;
  450. prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
  451. prependListener(
  452. event: "connectionAttemptFailed",
  453. listener: (ip: string, port: number, family: number, error: Error) => void,
  454. ): this;
  455. prependListener(
  456. event: "connectionAttemptTimeout",
  457. listener: (ip: string, port: number, family: number) => void,
  458. ): this;
  459. prependListener(event: "data", listener: (data: Buffer) => void): this;
  460. prependListener(event: "drain", listener: () => void): this;
  461. prependListener(event: "end", listener: () => void): this;
  462. prependListener(event: "error", listener: (err: Error) => void): this;
  463. prependListener(
  464. event: "lookup",
  465. listener: (err: Error, address: string, family: string | number, host: string) => void,
  466. ): this;
  467. prependListener(event: "ready", listener: () => void): this;
  468. prependListener(event: "timeout", listener: () => void): this;
  469. prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  470. prependOnceListener(event: "close", listener: (hadError: boolean) => void): this;
  471. prependOnceListener(event: "connect", listener: () => void): this;
  472. prependOnceListener(
  473. event: "connectionAttempt",
  474. listener: (ip: string, port: number, family: number) => void,
  475. ): this;
  476. prependOnceListener(
  477. event: "connectionAttemptFailed",
  478. listener: (ip: string, port: number, family: number, error: Error) => void,
  479. ): this;
  480. prependOnceListener(
  481. event: "connectionAttemptTimeout",
  482. listener: (ip: string, port: number, family: number) => void,
  483. ): this;
  484. prependOnceListener(event: "data", listener: (data: Buffer) => void): this;
  485. prependOnceListener(event: "drain", listener: () => void): this;
  486. prependOnceListener(event: "end", listener: () => void): this;
  487. prependOnceListener(event: "error", listener: (err: Error) => void): this;
  488. prependOnceListener(
  489. event: "lookup",
  490. listener: (err: Error, address: string, family: string | number, host: string) => void,
  491. ): this;
  492. prependOnceListener(event: "ready", listener: () => void): this;
  493. prependOnceListener(event: "timeout", listener: () => void): this;
  494. }
  495. interface ListenOptions extends Abortable {
  496. backlog?: number | undefined;
  497. exclusive?: boolean | undefined;
  498. host?: string | undefined;
  499. /**
  500. * @default false
  501. */
  502. ipv6Only?: boolean | undefined;
  503. reusePort?: boolean | undefined;
  504. path?: string | undefined;
  505. port?: number | undefined;
  506. readableAll?: boolean | undefined;
  507. writableAll?: boolean | undefined;
  508. }
  509. interface ServerOpts {
  510. /**
  511. * Indicates whether half-opened TCP connections are allowed.
  512. * @default false
  513. */
  514. allowHalfOpen?: boolean | undefined;
  515. /**
  516. * Indicates whether the socket should be paused on incoming connections.
  517. * @default false
  518. */
  519. pauseOnConnect?: boolean | undefined;
  520. /**
  521. * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received.
  522. * @default false
  523. * @since v16.5.0
  524. */
  525. noDelay?: boolean | undefined;
  526. /**
  527. * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received,
  528. * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`.
  529. * @default false
  530. * @since v16.5.0
  531. */
  532. keepAlive?: boolean | undefined;
  533. /**
  534. * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.
  535. * @default 0
  536. * @since v16.5.0
  537. */
  538. keepAliveInitialDelay?: number | undefined;
  539. /**
  540. * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`.
  541. * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode).
  542. * @since v18.17.0, v20.1.0
  543. */
  544. highWaterMark?: number | undefined;
  545. /**
  546. * `blockList` can be used for disabling inbound
  547. * access to specific IP addresses, IP ranges, or IP subnets. This does not
  548. * work if the server is behind a reverse proxy, NAT, etc. because the address
  549. * checked against the block list is the address of the proxy, or the one
  550. * specified by the NAT.
  551. * @since v22.13.0
  552. */
  553. blockList?: BlockList | undefined;
  554. }
  555. interface DropArgument {
  556. localAddress?: string;
  557. localPort?: number;
  558. localFamily?: string;
  559. remoteAddress?: string;
  560. remotePort?: number;
  561. remoteFamily?: string;
  562. }
  563. /**
  564. * This class is used to create a TCP or `IPC` server.
  565. * @since v0.1.90
  566. */
  567. class Server extends EventEmitter {
  568. constructor(connectionListener?: (socket: Socket) => void);
  569. constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void);
  570. /**
  571. * Start a server listening for connections. A `net.Server` can be a TCP or
  572. * an `IPC` server depending on what it listens to.
  573. *
  574. * Possible signatures:
  575. *
  576. * * `server.listen(handle[, backlog][, callback])`
  577. * * `server.listen(options[, callback])`
  578. * * `server.listen(path[, backlog][, callback])` for `IPC` servers
  579. * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers
  580. *
  581. * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'`
  582. * event.
  583. *
  584. * All `listen()` methods can take a `backlog` parameter to specify the maximum
  585. * length of the queue of pending connections. The actual length will be determined
  586. * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512).
  587. *
  588. * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for
  589. * details).
  590. *
  591. * The `server.listen()` method can be called again if and only if there was an
  592. * error during the first `server.listen()` call or `server.close()` has been
  593. * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.
  594. *
  595. * One of the most common errors raised when listening is `EADDRINUSE`.
  596. * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry
  597. * after a certain amount of time:
  598. *
  599. * ```js
  600. * server.on('error', (e) => {
  601. * if (e.code === 'EADDRINUSE') {
  602. * console.error('Address in use, retrying...');
  603. * setTimeout(() => {
  604. * server.close();
  605. * server.listen(PORT, HOST);
  606. * }, 1000);
  607. * }
  608. * });
  609. * ```
  610. */
  611. listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this;
  612. listen(port?: number, hostname?: string, listeningListener?: () => void): this;
  613. listen(port?: number, backlog?: number, listeningListener?: () => void): this;
  614. listen(port?: number, listeningListener?: () => void): this;
  615. listen(path: string, backlog?: number, listeningListener?: () => void): this;
  616. listen(path: string, listeningListener?: () => void): this;
  617. listen(options: ListenOptions, listeningListener?: () => void): this;
  618. listen(handle: any, backlog?: number, listeningListener?: () => void): this;
  619. listen(handle: any, listeningListener?: () => void): this;
  620. /**
  621. * Stops the server from accepting new connections and keeps existing
  622. * connections. This function is asynchronous, the server is finally closed
  623. * when all connections are ended and the server emits a `'close'` event.
  624. * The optional `callback` will be called once the `'close'` event occurs. Unlike
  625. * that event, it will be called with an `Error` as its only argument if the server
  626. * was not open when it was closed.
  627. * @since v0.1.90
  628. * @param callback Called when the server is closed.
  629. */
  630. close(callback?: (err?: Error) => void): this;
  631. /**
  632. * Returns the bound `address`, the address `family` name, and `port` of the server
  633. * as reported by the operating system if listening on an IP socket
  634. * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
  635. *
  636. * For a server listening on a pipe or Unix domain socket, the name is returned
  637. * as a string.
  638. *
  639. * ```js
  640. * const server = net.createServer((socket) => {
  641. * socket.end('goodbye\n');
  642. * }).on('error', (err) => {
  643. * // Handle errors here.
  644. * throw err;
  645. * });
  646. *
  647. * // Grab an arbitrary unused port.
  648. * server.listen(() => {
  649. * console.log('opened server on', server.address());
  650. * });
  651. * ```
  652. *
  653. * `server.address()` returns `null` before the `'listening'` event has been
  654. * emitted or after calling `server.close()`.
  655. * @since v0.1.90
  656. */
  657. address(): AddressInfo | string | null;
  658. /**
  659. * Asynchronously get the number of concurrent connections on the server. Works
  660. * when sockets were sent to forks.
  661. *
  662. * Callback should take two arguments `err` and `count`.
  663. * @since v0.9.7
  664. */
  665. getConnections(cb: (error: Error | null, count: number) => void): void;
  666. /**
  667. * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior).
  668. * If the server is `ref`ed calling `ref()` again will have no effect.
  669. * @since v0.9.1
  670. */
  671. ref(): this;
  672. /**
  673. * Calling `unref()` on a server will allow the program to exit if this is the only
  674. * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect.
  675. * @since v0.9.1
  676. */
  677. unref(): this;
  678. /**
  679. * Set this property to reject connections when the server's connection count gets
  680. * high.
  681. *
  682. * It is not recommended to use this option once a socket has been sent to a child
  683. * with `child_process.fork()`.
  684. * @since v0.2.0
  685. */
  686. maxConnections: number;
  687. connections: number;
  688. /**
  689. * Indicates whether or not the server is listening for connections.
  690. * @since v5.7.0
  691. */
  692. readonly listening: boolean;
  693. /**
  694. * events.EventEmitter
  695. * 1. close
  696. * 2. connection
  697. * 3. error
  698. * 4. listening
  699. * 5. drop
  700. */
  701. addListener(event: string, listener: (...args: any[]) => void): this;
  702. addListener(event: "close", listener: () => void): this;
  703. addListener(event: "connection", listener: (socket: Socket) => void): this;
  704. addListener(event: "error", listener: (err: Error) => void): this;
  705. addListener(event: "listening", listener: () => void): this;
  706. addListener(event: "drop", listener: (data?: DropArgument) => void): this;
  707. emit(event: string | symbol, ...args: any[]): boolean;
  708. emit(event: "close"): boolean;
  709. emit(event: "connection", socket: Socket): boolean;
  710. emit(event: "error", err: Error): boolean;
  711. emit(event: "listening"): boolean;
  712. emit(event: "drop", data?: DropArgument): boolean;
  713. on(event: string, listener: (...args: any[]) => void): this;
  714. on(event: "close", listener: () => void): this;
  715. on(event: "connection", listener: (socket: Socket) => void): this;
  716. on(event: "error", listener: (err: Error) => void): this;
  717. on(event: "listening", listener: () => void): this;
  718. on(event: "drop", listener: (data?: DropArgument) => void): this;
  719. once(event: string, listener: (...args: any[]) => void): this;
  720. once(event: "close", listener: () => void): this;
  721. once(event: "connection", listener: (socket: Socket) => void): this;
  722. once(event: "error", listener: (err: Error) => void): this;
  723. once(event: "listening", listener: () => void): this;
  724. once(event: "drop", listener: (data?: DropArgument) => void): this;
  725. prependListener(event: string, listener: (...args: any[]) => void): this;
  726. prependListener(event: "close", listener: () => void): this;
  727. prependListener(event: "connection", listener: (socket: Socket) => void): this;
  728. prependListener(event: "error", listener: (err: Error) => void): this;
  729. prependListener(event: "listening", listener: () => void): this;
  730. prependListener(event: "drop", listener: (data?: DropArgument) => void): this;
  731. prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  732. prependOnceListener(event: "close", listener: () => void): this;
  733. prependOnceListener(event: "connection", listener: (socket: Socket) => void): this;
  734. prependOnceListener(event: "error", listener: (err: Error) => void): this;
  735. prependOnceListener(event: "listening", listener: () => void): this;
  736. prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this;
  737. /**
  738. * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed.
  739. * @since v20.5.0
  740. */
  741. [Symbol.asyncDispose](): Promise<void>;
  742. }
  743. type IPVersion = "ipv4" | "ipv6";
  744. /**
  745. * The `BlockList` object can be used with some network APIs to specify rules for
  746. * disabling inbound or outbound access to specific IP addresses, IP ranges, or
  747. * IP subnets.
  748. * @since v15.0.0, v14.18.0
  749. */
  750. class BlockList {
  751. /**
  752. * Adds a rule to block the given IP address.
  753. * @since v15.0.0, v14.18.0
  754. * @param address An IPv4 or IPv6 address.
  755. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
  756. */
  757. addAddress(address: string, type?: IPVersion): void;
  758. addAddress(address: SocketAddress): void;
  759. /**
  760. * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive).
  761. * @since v15.0.0, v14.18.0
  762. * @param start The starting IPv4 or IPv6 address in the range.
  763. * @param end The ending IPv4 or IPv6 address in the range.
  764. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
  765. */
  766. addRange(start: string, end: string, type?: IPVersion): void;
  767. addRange(start: SocketAddress, end: SocketAddress): void;
  768. /**
  769. * Adds a rule to block a range of IP addresses specified as a subnet mask.
  770. * @since v15.0.0, v14.18.0
  771. * @param net The network IPv4 or IPv6 address.
  772. * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`.
  773. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
  774. */
  775. addSubnet(net: SocketAddress, prefix: number): void;
  776. addSubnet(net: string, prefix: number, type?: IPVersion): void;
  777. /**
  778. * Returns `true` if the given IP address matches any of the rules added to the`BlockList`.
  779. *
  780. * ```js
  781. * const blockList = new net.BlockList();
  782. * blockList.addAddress('123.123.123.123');
  783. * blockList.addRange('10.0.0.1', '10.0.0.10');
  784. * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
  785. *
  786. * console.log(blockList.check('123.123.123.123')); // Prints: true
  787. * console.log(blockList.check('10.0.0.3')); // Prints: true
  788. * console.log(blockList.check('222.111.111.222')); // Prints: false
  789. *
  790. * // IPv6 notation for IPv4 addresses works:
  791. * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
  792. * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
  793. * ```
  794. * @since v15.0.0, v14.18.0
  795. * @param address The IP address to check
  796. * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
  797. */
  798. check(address: SocketAddress): boolean;
  799. check(address: string, type?: IPVersion): boolean;
  800. /**
  801. * The list of rules added to the blocklist.
  802. * @since v15.0.0, v14.18.0
  803. */
  804. rules: readonly string[];
  805. /**
  806. * Returns `true` if the `value` is a `net.BlockList`.
  807. * @since v22.13.0
  808. * @param value Any JS value
  809. */
  810. static isBlockList(value: unknown): value is BlockList;
  811. }
  812. interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
  813. timeout?: number | undefined;
  814. }
  815. interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts {
  816. timeout?: number | undefined;
  817. }
  818. type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts;
  819. /**
  820. * Creates a new TCP or `IPC` server.
  821. *
  822. * If `allowHalfOpen` is set to `true`, when the other end of the socket
  823. * signals the end of transmission, the server will only send back the end of
  824. * transmission when `socket.end()` is explicitly called. For example, in the
  825. * context of TCP, when a FIN packed is received, a FIN packed is sent
  826. * back only when `socket.end()` is explicitly called. Until then the
  827. * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information.
  828. *
  829. * If `pauseOnConnect` is set to `true`, then the socket associated with each
  830. * incoming connection will be paused, and no data will be read from its handle.
  831. * This allows connections to be passed between processes without any data being
  832. * read by the original process. To begin reading data from a paused socket, call `socket.resume()`.
  833. *
  834. * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to.
  835. *
  836. * Here is an example of a TCP echo server which listens for connections
  837. * on port 8124:
  838. *
  839. * ```js
  840. * import net from 'node:net';
  841. * const server = net.createServer((c) => {
  842. * // 'connection' listener.
  843. * console.log('client connected');
  844. * c.on('end', () => {
  845. * console.log('client disconnected');
  846. * });
  847. * c.write('hello\r\n');
  848. * c.pipe(c);
  849. * });
  850. * server.on('error', (err) => {
  851. * throw err;
  852. * });
  853. * server.listen(8124, () => {
  854. * console.log('server bound');
  855. * });
  856. * ```
  857. *
  858. * Test this by using `telnet`:
  859. *
  860. * ```bash
  861. * telnet localhost 8124
  862. * ```
  863. *
  864. * To listen on the socket `/tmp/echo.sock`:
  865. *
  866. * ```js
  867. * server.listen('/tmp/echo.sock', () => {
  868. * console.log('server bound');
  869. * });
  870. * ```
  871. *
  872. * Use `nc` to connect to a Unix domain socket server:
  873. *
  874. * ```bash
  875. * nc -U /tmp/echo.sock
  876. * ```
  877. * @since v0.5.0
  878. * @param connectionListener Automatically set as a listener for the {@link 'connection'} event.
  879. */
  880. function createServer(connectionListener?: (socket: Socket) => void): Server;
  881. function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server;
  882. /**
  883. * Aliases to {@link createConnection}.
  884. *
  885. * Possible signatures:
  886. *
  887. * * {@link connect}
  888. * * {@link connect} for `IPC` connections.
  889. * * {@link connect} for TCP connections.
  890. */
  891. function connect(options: NetConnectOpts, connectionListener?: () => void): Socket;
  892. function connect(port: number, host?: string, connectionListener?: () => void): Socket;
  893. function connect(path: string, connectionListener?: () => void): Socket;
  894. /**
  895. * A factory function, which creates a new {@link Socket},
  896. * immediately initiates connection with `socket.connect()`,
  897. * then returns the `net.Socket` that starts the connection.
  898. *
  899. * When the connection is established, a `'connect'` event will be emitted
  900. * on the returned socket. The last parameter `connectListener`, if supplied,
  901. * will be added as a listener for the `'connect'` event **once**.
  902. *
  903. * Possible signatures:
  904. *
  905. * * {@link createConnection}
  906. * * {@link createConnection} for `IPC` connections.
  907. * * {@link createConnection} for TCP connections.
  908. *
  909. * The {@link connect} function is an alias to this function.
  910. */
  911. function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket;
  912. function createConnection(port: number, host?: string, connectionListener?: () => void): Socket;
  913. function createConnection(path: string, connectionListener?: () => void): Socket;
  914. /**
  915. * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`.
  916. * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided.
  917. * @since v19.4.0
  918. */
  919. function getDefaultAutoSelectFamily(): boolean;
  920. /**
  921. * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`.
  922. * @param value The new default value.
  923. * The initial default value is `true`, unless the command line option
  924. * `--no-network-family-autoselection` is provided.
  925. * @since v19.4.0
  926. */
  927. function setDefaultAutoSelectFamily(value: boolean): void;
  928. /**
  929. * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
  930. * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`.
  931. * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option.
  932. * @since v19.8.0, v18.8.0
  933. */
  934. function getDefaultAutoSelectFamilyAttemptTimeout(): number;
  935. /**
  936. * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
  937. * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line
  938. * option `--network-family-autoselection-attempt-timeout`.
  939. * @since v19.8.0, v18.8.0
  940. */
  941. function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void;
  942. /**
  943. * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4
  944. * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`.
  945. *
  946. * ```js
  947. * net.isIP('::1'); // returns 6
  948. * net.isIP('127.0.0.1'); // returns 4
  949. * net.isIP('127.000.000.001'); // returns 0
  950. * net.isIP('127.0.0.1/24'); // returns 0
  951. * net.isIP('fhqwhgads'); // returns 0
  952. * ```
  953. * @since v0.3.0
  954. */
  955. function isIP(input: string): number;
  956. /**
  957. * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no
  958. * leading zeroes. Otherwise, returns `false`.
  959. *
  960. * ```js
  961. * net.isIPv4('127.0.0.1'); // returns true
  962. * net.isIPv4('127.000.000.001'); // returns false
  963. * net.isIPv4('127.0.0.1/24'); // returns false
  964. * net.isIPv4('fhqwhgads'); // returns false
  965. * ```
  966. * @since v0.3.0
  967. */
  968. function isIPv4(input: string): boolean;
  969. /**
  970. * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`.
  971. *
  972. * ```js
  973. * net.isIPv6('::1'); // returns true
  974. * net.isIPv6('fhqwhgads'); // returns false
  975. * ```
  976. * @since v0.3.0
  977. */
  978. function isIPv6(input: string): boolean;
  979. interface SocketAddressInitOptions {
  980. /**
  981. * The network address as either an IPv4 or IPv6 string.
  982. * @default 127.0.0.1
  983. */
  984. address?: string | undefined;
  985. /**
  986. * @default `'ipv4'`
  987. */
  988. family?: IPVersion | undefined;
  989. /**
  990. * An IPv6 flow-label used only if `family` is `'ipv6'`.
  991. * @default 0
  992. */
  993. flowlabel?: number | undefined;
  994. /**
  995. * An IP port.
  996. * @default 0
  997. */
  998. port?: number | undefined;
  999. }
  1000. /**
  1001. * @since v15.14.0, v14.18.0
  1002. */
  1003. class SocketAddress {
  1004. constructor(options: SocketAddressInitOptions);
  1005. /**
  1006. * Either \`'ipv4'\` or \`'ipv6'\`.
  1007. * @since v15.14.0, v14.18.0
  1008. */
  1009. readonly address: string;
  1010. /**
  1011. * Either \`'ipv4'\` or \`'ipv6'\`.
  1012. * @since v15.14.0, v14.18.0
  1013. */
  1014. readonly family: IPVersion;
  1015. /**
  1016. * @since v15.14.0, v14.18.0
  1017. */
  1018. readonly port: number;
  1019. /**
  1020. * @since v15.14.0, v14.18.0
  1021. */
  1022. readonly flowlabel: number;
  1023. /**
  1024. * @since v22.13.0
  1025. * @param input An input string containing an IP address and optional port,
  1026. * e.g. `123.1.2.3:1234` or `[1::1]:1234`.
  1027. * @returns Returns a `SocketAddress` if parsing was successful.
  1028. * Otherwise returns `undefined`.
  1029. */
  1030. static parse(input: string): SocketAddress | undefined;
  1031. }
  1032. }
  1033. declare module "node:net" {
  1034. export * from "net";
  1035. }