8e5c7c44f3fdf078b0cf42c38936207f2f99d31b9a3e5ad646649a08a13f68e94fe5ffb5eec8744b03cfc11780c7cf049aaf0b75c7e9bffaae4ba510e2a496 47 KB

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