UNPKG

36.8 kBTypeScriptView Raw
1/**
2 * > Stability: 2 - Stable
3 *
4 * The `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 * const net = require('net');
12 * ```
13 * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/net.js)
14 */
15declare 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 = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void;
20 interface AddressInfo {
21 address: string;
22 family: string;
23 port: number;
24 }
25 interface SocketConstructorOpts {
26 fd?: number | undefined;
27 allowHalfOpen?: boolean | undefined;
28 readable?: boolean | undefined;
29 writable?: boolean | undefined;
30 signal?: AbortSignal;
31 }
32 interface OnReadOpts {
33 buffer: Uint8Array | (() => Uint8Array);
34 /**
35 * This function is called for every chunk of incoming data.
36 * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer.
37 * Return false from this function to implicitly pause() the socket.
38 */
39 callback(bytesWritten: number, buf: Uint8Array): boolean;
40 }
41 interface ConnectOpts {
42 /**
43 * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
44 * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
45 * still be emitted as normal and methods like pause() and resume() will also behave as expected.
46 */
47 onread?: OnReadOpts | undefined;
48 }
49 interface TcpSocketConnectOpts extends ConnectOpts {
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 }
58 interface IpcSocketConnectOpts extends ConnectOpts {
59 path: string;
60 }
61 type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
62 type SocketReadyState = 'opening' | 'open' | 'readOnly' | 'writeOnly' | 'closed';
63 /**
64 * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint
65 * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also
66 * an `EventEmitter`.
67 *
68 * A `net.Socket` can be created by the user and used directly to interact with
69 * a server. For example, it is returned by {@link createConnection},
70 * so the user can use it to talk to the server.
71 *
72 * It can also be created by Node.js and passed to the user when a connection
73 * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use
74 * it to interact with the client.
75 * @since v0.3.4
76 */
77 class Socket extends stream.Duplex {
78 constructor(options?: SocketConstructorOpts);
79 /**
80 * Sends data on the socket. The second parameter specifies the encoding in the
81 * case of a string. It defaults to UTF8 encoding.
82 *
83 * Returns `true` if the entire data was flushed successfully to the kernel
84 * 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.
85 *
86 * The optional `callback` parameter will be executed when the data is finally
87 * written out, which may not be immediately.
88 *
89 * See `Writable` stream `write()` method for more
90 * information.
91 * @since v0.1.90
92 * @param [encoding='utf8'] Only used when data is `string`.
93 */
94 write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
95 write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean;
96 /**
97 * Initiate a connection on a given socket.
98 *
99 * Possible signatures:
100 *
101 * * `socket.connect(options[, connectListener])`
102 * * `socket.connect(path[, connectListener])` for `IPC` connections.
103 * * `socket.connect(port[, host][, connectListener])` for TCP connections.
104 * * Returns: `net.Socket` The socket itself.
105 *
106 * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting,
107 * instead of a `'connect'` event, an `'error'` event will be emitted with
108 * the error passed to the `'error'` listener.
109 * The last parameter `connectListener`, if supplied, will be added as a listener
110 * for the `'connect'` event **once**.
111 *
112 * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined
113 * behavior.
114 */
115 connect(options: SocketConnectOpts, connectionListener?: () => void): this;
116 connect(port: number, host: string, connectionListener?: () => void): this;
117 connect(port: number, connectionListener?: () => void): this;
118 connect(path: string, connectionListener?: () => void): this;
119 /**
120 * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information.
121 * @since v0.1.90
122 * @return The socket itself.
123 */
124 setEncoding(encoding?: BufferEncoding): this;
125 /**
126 * Pauses the reading of data. That is, `'data'` events will not be emitted.
127 * Useful to throttle back an upload.
128 * @return The socket itself.
129 */
130 pause(): this;
131 /**
132 * Resumes reading after a call to `socket.pause()`.
133 * @return The socket itself.
134 */
135 resume(): this;
136 /**
137 * Sets the socket to timeout after `timeout` milliseconds of inactivity on
138 * the socket. By default `net.Socket` do not have a timeout.
139 *
140 * 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
141 * end the connection.
142 *
143 * ```js
144 * socket.setTimeout(3000);
145 * socket.on('timeout', () => {
146 * console.log('socket timeout');
147 * socket.end();
148 * });
149 * ```
150 *
151 * If `timeout` is 0, then the existing idle timeout is disabled.
152 *
153 * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event.
154 * @since v0.1.90
155 * @return The socket itself.
156 */
157 setTimeout(timeout: number, callback?: () => void): this;
158 /**
159 * Enable/disable the use of Nagle's algorithm.
160 *
161 * When a TCP connection is created, it will have Nagle's algorithm enabled.
162 *
163 * Nagle's algorithm delays data before it is sent via the network. It attempts
164 * to optimize throughput at the expense of latency.
165 *
166 * Passing `true` for `noDelay` or not passing an argument will disable Nagle's
167 * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's
168 * algorithm.
169 * @since v0.1.90
170 * @param [noDelay=true]
171 * @return The socket itself.
172 */
173 setNoDelay(noDelay?: boolean): this;
174 /**
175 * Enable/disable keep-alive functionality, and optionally set the initial
176 * delay before the first keepalive probe is sent on an idle socket.
177 *
178 * Set `initialDelay` (in milliseconds) to set the delay between the last
179 * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default
180 * (or previous) setting.
181 *
182 * Enabling the keep-alive functionality will set the following socket options:
183 *
184 * * `SO_KEEPALIVE=1`
185 * * `TCP_KEEPIDLE=initialDelay`
186 * * `TCP_KEEPCNT=10`
187 * * `TCP_KEEPINTVL=1`
188 * @since v0.1.92
189 * @param [enable=false]
190 * @param [initialDelay=0]
191 * @return The socket itself.
192 */
193 setKeepAlive(enable?: boolean, initialDelay?: number): this;
194 /**
195 * Returns the bound `address`, the address `family` name and `port` of the
196 * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
197 * @since v0.1.90
198 */
199 address(): AddressInfo | {};
200 /**
201 * Calling `unref()` on a socket will allow the program to exit if this is the only
202 * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect.
203 * @since v0.9.1
204 * @return The socket itself.
205 */
206 unref(): this;
207 /**
208 * 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).
209 * If the socket is `ref`ed calling `ref` again will have no effect.
210 * @since v0.9.1
211 * @return The socket itself.
212 */
213 ref(): this;
214 /**
215 * This property shows the number of characters buffered for writing. The buffer
216 * may contain strings whose length after encoding is not yet known. So this number
217 * is only an approximation of the number of bytes in the buffer.
218 *
219 * `net.Socket` has the property that `socket.write()` always works. This is to
220 * help users get up and running quickly. The computer cannot always keep up
221 * with the amount of data that is written to a socket. The network connection
222 * simply might be too slow. Node.js will internally queue up the data written to a
223 * socket and send it out over the wire when it is possible.
224 *
225 * The consequence of this internal buffering is that memory may grow.
226 * Users who experience large or growing `bufferSize` should attempt to
227 * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`.
228 * @since v0.3.8
229 * @deprecated Since v14.6.0 - Use `writableLength` instead.
230 */
231 readonly bufferSize: number;
232 /**
233 * The amount of received bytes.
234 * @since v0.5.3
235 */
236 readonly bytesRead: number;
237 /**
238 * The amount of bytes sent.
239 * @since v0.5.3
240 */
241 readonly bytesWritten: number;
242 /**
243 * If `true`,`socket.connect(options[, connectListener])` was
244 * called and has not yet finished. It will stay `true` until the socket becomes
245 * connected, then it is set to `false` and the `'connect'` event is emitted. Note
246 * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event.
247 * @since v6.1.0
248 */
249 readonly connecting: boolean;
250 /**
251 * See `writable.destroyed` for further details.
252 */
253 readonly destroyed: boolean;
254 /**
255 * The string representation of the local IP address the remote client is
256 * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
257 * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`.
258 * @since v0.9.6
259 */
260 readonly localAddress?: string;
261 /**
262 * The numeric representation of the local port. For example, `80` or `21`.
263 * @since v0.9.6
264 */
265 readonly localPort?: number;
266 /**
267 * This property represents the state of the connection as a string.
268 * @see {https://nodejs.org/api/net.html#socketreadystate}
269 * @since v0.5.0
270 */
271 readonly readyState: SocketReadyState;
272 /**
273 * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if
274 * the socket is destroyed (for example, if the client disconnected).
275 * @since v0.5.10
276 */
277 readonly remoteAddress?: string | undefined;
278 /**
279 * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
280 * @since v0.11.14
281 */
282 readonly remoteFamily?: string | undefined;
283 /**
284 * The numeric representation of the remote port. For example, `80` or `21`.
285 * @since v0.5.10
286 */
287 readonly remotePort?: number | undefined;
288 /**
289 * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set.
290 * @since v10.7.0
291 */
292 readonly timeout?: number | undefined;
293 /**
294 * Half-closes the socket. i.e., it sends a FIN packet. It is possible the
295 * server will still send some data.
296 *
297 * See `writable.end()` for further details.
298 * @since v0.1.90
299 * @param [encoding='utf8'] Only used when data is `string`.
300 * @param callback Optional callback for when the socket is finished.
301 * @return The socket itself.
302 */
303 end(callback?: () => void): this;
304 end(buffer: Uint8Array | string, callback?: () => void): this;
305 end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this;
306 /**
307 * events.EventEmitter
308 * 1. close
309 * 2. connect
310 * 3. data
311 * 4. drain
312 * 5. end
313 * 6. error
314 * 7. lookup
315 * 8. timeout
316 */
317 addListener(event: string, listener: (...args: any[]) => void): this;
318 addListener(event: 'close', listener: (hadError: boolean) => void): this;
319 addListener(event: 'connect', listener: () => void): this;
320 addListener(event: 'data', listener: (data: Buffer) => void): this;
321 addListener(event: 'drain', listener: () => void): this;
322 addListener(event: 'end', listener: () => void): this;
323 addListener(event: 'error', listener: (err: Error) => void): this;
324 addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
325 addListener(event: 'ready', listener: () => void): this;
326 addListener(event: 'timeout', listener: () => void): this;
327 emit(event: string | symbol, ...args: any[]): boolean;
328 emit(event: 'close', hadError: boolean): boolean;
329 emit(event: 'connect'): boolean;
330 emit(event: 'data', data: Buffer): boolean;
331 emit(event: 'drain'): boolean;
332 emit(event: 'end'): boolean;
333 emit(event: 'error', err: Error): boolean;
334 emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean;
335 emit(event: 'ready'): boolean;
336 emit(event: 'timeout'): boolean;
337 on(event: string, listener: (...args: any[]) => void): this;
338 on(event: 'close', listener: (hadError: boolean) => void): this;
339 on(event: 'connect', listener: () => void): this;
340 on(event: 'data', listener: (data: Buffer) => void): this;
341 on(event: 'drain', listener: () => void): this;
342 on(event: 'end', listener: () => void): this;
343 on(event: 'error', listener: (err: Error) => void): this;
344 on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
345 on(event: 'ready', listener: () => void): this;
346 on(event: 'timeout', listener: () => void): this;
347 once(event: string, listener: (...args: any[]) => void): this;
348 once(event: 'close', listener: (hadError: boolean) => void): this;
349 once(event: 'connect', listener: () => void): this;
350 once(event: 'data', listener: (data: Buffer) => void): this;
351 once(event: 'drain', listener: () => void): this;
352 once(event: 'end', listener: () => void): this;
353 once(event: 'error', listener: (err: Error) => void): this;
354 once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
355 once(event: 'ready', listener: () => void): this;
356 once(event: 'timeout', listener: () => void): this;
357 prependListener(event: string, listener: (...args: any[]) => void): this;
358 prependListener(event: 'close', listener: (hadError: boolean) => void): this;
359 prependListener(event: 'connect', listener: () => void): this;
360 prependListener(event: 'data', listener: (data: Buffer) => void): this;
361 prependListener(event: 'drain', listener: () => void): this;
362 prependListener(event: 'end', listener: () => void): this;
363 prependListener(event: 'error', listener: (err: Error) => void): this;
364 prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
365 prependListener(event: 'ready', listener: () => void): this;
366 prependListener(event: 'timeout', listener: () => void): this;
367 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
368 prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this;
369 prependOnceListener(event: 'connect', listener: () => void): this;
370 prependOnceListener(event: 'data', listener: (data: Buffer) => void): this;
371 prependOnceListener(event: 'drain', listener: () => void): this;
372 prependOnceListener(event: 'end', listener: () => void): this;
373 prependOnceListener(event: 'error', listener: (err: Error) => void): this;
374 prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this;
375 prependOnceListener(event: 'ready', listener: () => void): this;
376 prependOnceListener(event: 'timeout', listener: () => void): this;
377 }
378 interface ListenOptions extends Abortable {
379 port?: number | undefined;
380 host?: string | undefined;
381 backlog?: number | undefined;
382 path?: string | undefined;
383 exclusive?: boolean | undefined;
384 readableAll?: boolean | undefined;
385 writableAll?: boolean | undefined;
386 /**
387 * @default false
388 */
389 ipv6Only?: boolean | undefined;
390 }
391 interface ServerOpts {
392 /**
393 * Indicates whether half-opened TCP connections are allowed.
394 * @default false
395 */
396 allowHalfOpen?: boolean | undefined;
397 /**
398 * Indicates whether the socket should be paused on incoming connections.
399 * @default false
400 */
401 pauseOnConnect?: boolean | undefined;
402 }
403 /**
404 * This class is used to create a TCP or `IPC` server.
405 * @since v0.1.90
406 */
407 class Server extends EventEmitter {
408 constructor(connectionListener?: (socket: Socket) => void);
409 constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void);
410 /**
411 * Start a server listening for connections. A `net.Server` can be a TCP or
412 * an `IPC` server depending on what it listens to.
413 *
414 * Possible signatures:
415 *
416 * * `server.listen(handle[, backlog][, callback])`
417 * * `server.listen(options[, callback])`
418 * * `server.listen(path[, backlog][, callback])` for `IPC` servers
419 * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers
420 *
421 * 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'`
422 * event.
423 *
424 * All `listen()` methods can take a `backlog` parameter to specify the maximum
425 * length of the queue of pending connections. The actual length will be determined
426 * 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).
427 *
428 * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for
429 * details).
430 *
431 * The `server.listen()` method can be called again if and only if there was an
432 * error during the first `server.listen()` call or `server.close()` has been
433 * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.
434 *
435 * One of the most common errors raised when listening is `EADDRINUSE`.
436 * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry
437 * after a certain amount of time:
438 *
439 * ```js
440 * server.on('error', (e) => {
441 * if (e.code === 'EADDRINUSE') {
442 * console.log('Address in use, retrying...');
443 * setTimeout(() => {
444 * server.close();
445 * server.listen(PORT, HOST);
446 * }, 1000);
447 * }
448 * });
449 * ```
450 */
451 listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this;
452 listen(port?: number, hostname?: string, listeningListener?: () => void): this;
453 listen(port?: number, backlog?: number, listeningListener?: () => void): this;
454 listen(port?: number, listeningListener?: () => void): this;
455 listen(path: string, backlog?: number, listeningListener?: () => void): this;
456 listen(path: string, listeningListener?: () => void): this;
457 listen(options: ListenOptions, listeningListener?: () => void): this;
458 listen(handle: any, backlog?: number, listeningListener?: () => void): this;
459 listen(handle: any, listeningListener?: () => void): this;
460 /**
461 * Stops the server from accepting new connections and keeps existing
462 * connections. This function is asynchronous, the server is finally closed
463 * when all connections are ended and the server emits a `'close'` event.
464 * The optional `callback` will be called once the `'close'` event occurs. Unlike
465 * that event, it will be called with an `Error` as its only argument if the server
466 * was not open when it was closed.
467 * @since v0.1.90
468 * @param callback Called when the server is closed.
469 */
470 close(callback?: (err?: Error) => void): this;
471 /**
472 * Returns the bound `address`, the address `family` name, and `port` of the server
473 * as reported by the operating system if listening on an IP socket
474 * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
475 *
476 * For a server listening on a pipe or Unix domain socket, the name is returned
477 * as a string.
478 *
479 * ```js
480 * const server = net.createServer((socket) => {
481 * socket.end('goodbye\n');
482 * }).on('error', (err) => {
483 * // Handle errors here.
484 * throw err;
485 * });
486 *
487 * // Grab an arbitrary unused port.
488 * server.listen(() => {
489 * console.log('opened server on', server.address());
490 * });
491 * ```
492 *
493 * `server.address()` returns `null` before the `'listening'` event has been
494 * emitted or after calling `server.close()`.
495 * @since v0.1.90
496 */
497 address(): AddressInfo | string | null;
498 /**
499 * Asynchronously get the number of concurrent connections on the server. Works
500 * when sockets were sent to forks.
501 *
502 * Callback should take two arguments `err` and `count`.
503 * @since v0.9.7
504 */
505 getConnections(cb: (error: Error | null, count: number) => void): void;
506 /**
507 * 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).
508 * If the server is `ref`ed calling `ref()` again will have no effect.
509 * @since v0.9.1
510 */
511 ref(): this;
512 /**
513 * Calling `unref()` on a server will allow the program to exit if this is the only
514 * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect.
515 * @since v0.9.1
516 */
517 unref(): this;
518 /**
519 * Set this property to reject connections when the server's connection count gets
520 * high.
521 *
522 * It is not recommended to use this option once a socket has been sent to a child
523 * with `child_process.fork()`.
524 * @since v0.2.0
525 */
526 maxConnections: number;
527 connections: number;
528 /**
529 * Indicates whether or not the server is listening for connections.
530 * @since v5.7.0
531 */
532 listening: boolean;
533 /**
534 * events.EventEmitter
535 * 1. close
536 * 2. connection
537 * 3. error
538 * 4. listening
539 */
540 addListener(event: string, listener: (...args: any[]) => void): this;
541 addListener(event: 'close', listener: () => void): this;
542 addListener(event: 'connection', listener: (socket: Socket) => void): this;
543 addListener(event: 'error', listener: (err: Error) => void): this;
544 addListener(event: 'listening', listener: () => void): this;
545 emit(event: string | symbol, ...args: any[]): boolean;
546 emit(event: 'close'): boolean;
547 emit(event: 'connection', socket: Socket): boolean;
548 emit(event: 'error', err: Error): boolean;
549 emit(event: 'listening'): boolean;
550 on(event: string, listener: (...args: any[]) => void): this;
551 on(event: 'close', listener: () => void): this;
552 on(event: 'connection', listener: (socket: Socket) => void): this;
553 on(event: 'error', listener: (err: Error) => void): this;
554 on(event: 'listening', listener: () => void): this;
555 once(event: string, listener: (...args: any[]) => void): this;
556 once(event: 'close', listener: () => void): this;
557 once(event: 'connection', listener: (socket: Socket) => void): this;
558 once(event: 'error', listener: (err: Error) => void): this;
559 once(event: 'listening', listener: () => void): this;
560 prependListener(event: string, listener: (...args: any[]) => void): this;
561 prependListener(event: 'close', listener: () => void): this;
562 prependListener(event: 'connection', listener: (socket: Socket) => void): this;
563 prependListener(event: 'error', listener: (err: Error) => void): this;
564 prependListener(event: 'listening', listener: () => void): this;
565 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
566 prependOnceListener(event: 'close', listener: () => void): this;
567 prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this;
568 prependOnceListener(event: 'error', listener: (err: Error) => void): this;
569 prependOnceListener(event: 'listening', listener: () => void): this;
570 }
571 type IPVersion = 'ipv4' | 'ipv6';
572 /**
573 * The `BlockList` object can be used with some network APIs to specify rules for
574 * disabling inbound or outbound access to specific IP addresses, IP ranges, or
575 * IP subnets.
576 * @since v15.0.0, v14.18.0
577 */
578 class BlockList {
579 /**
580 * Adds a rule to block the given IP address.
581 * @since v15.0.0, v14.18.0
582 * @param address An IPv4 or IPv6 address.
583 * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
584 */
585 addAddress(address: string, type?: IPVersion): void;
586 addAddress(address: SocketAddress): void;
587 /**
588 * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive).
589 * @since v15.0.0, v14.18.0
590 * @param start The starting IPv4 or IPv6 address in the range.
591 * @param end The ending IPv4 or IPv6 address in the range.
592 * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
593 */
594 addRange(start: string, end: string, type?: IPVersion): void;
595 addRange(start: SocketAddress, end: SocketAddress): void;
596 /**
597 * Adds a rule to block a range of IP addresses specified as a subnet mask.
598 * @since v15.0.0, v14.18.0
599 * @param net The network IPv4 or IPv6 address.
600 * @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`.
601 * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
602 */
603 addSubnet(net: SocketAddress, prefix: number): void;
604 addSubnet(net: string, prefix: number, type?: IPVersion): void;
605 /**
606 * Returns `true` if the given IP address matches any of the rules added to the`BlockList`.
607 *
608 * ```js
609 * const blockList = new net.BlockList();
610 * blockList.addAddress('123.123.123.123');
611 * blockList.addRange('10.0.0.1', '10.0.0.10');
612 * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
613 *
614 * console.log(blockList.check('123.123.123.123')); // Prints: true
615 * console.log(blockList.check('10.0.0.3')); // Prints: true
616 * console.log(blockList.check('222.111.111.222')); // Prints: false
617 *
618 * // IPv6 notation for IPv4 addresses works:
619 * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
620 * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
621 * ```
622 * @since v15.0.0, v14.18.0
623 * @param address The IP address to check
624 * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
625 */
626 check(address: SocketAddress): boolean;
627 check(address: string, type?: IPVersion): boolean;
628 }
629 interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
630 timeout?: number | undefined;
631 }
632 interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts {
633 timeout?: number | undefined;
634 }
635 type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts;
636 /**
637 * Creates a new TCP or `IPC` server.
638 *
639 * If `allowHalfOpen` is set to `true`, when the other end of the socket
640 * signals the end of transmission, the server will only send back the end of
641 * transmission when `socket.end()` is explicitly called. For example, in the
642 * context of TCP, when a FIN packed is received, a FIN packed is sent
643 * back only when `socket.end()` is explicitly called. Until then the
644 * 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.
645 *
646 * If `pauseOnConnect` is set to `true`, then the socket associated with each
647 * incoming connection will be paused, and no data will be read from its handle.
648 * This allows connections to be passed between processes without any data being
649 * read by the original process. To begin reading data from a paused socket, call `socket.resume()`.
650 *
651 * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to.
652 *
653 * Here is an example of an TCP echo server which listens for connections
654 * on port 8124:
655 *
656 * ```js
657 * const net = require('net');
658 * const server = net.createServer((c) => {
659 * // 'connection' listener.
660 * console.log('client connected');
661 * c.on('end', () => {
662 * console.log('client disconnected');
663 * });
664 * c.write('hello\r\n');
665 * c.pipe(c);
666 * });
667 * server.on('error', (err) => {
668 * throw err;
669 * });
670 * server.listen(8124, () => {
671 * console.log('server bound');
672 * });
673 * ```
674 *
675 * Test this by using `telnet`:
676 *
677 * ```console
678 * $ telnet localhost 8124
679 * ```
680 *
681 * To listen on the socket `/tmp/echo.sock`:
682 *
683 * ```js
684 * server.listen('/tmp/echo.sock', () => {
685 * console.log('server bound');
686 * });
687 * ```
688 *
689 * Use `nc` to connect to a Unix domain socket server:
690 *
691 * ```console
692 * $ nc -U /tmp/echo.sock
693 * ```
694 * @since v0.5.0
695 * @param connectionListener Automatically set as a listener for the {@link 'connection'} event.
696 */
697 function createServer(connectionListener?: (socket: Socket) => void): Server;
698 function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server;
699 /**
700 * Aliases to {@link createConnection}.
701 *
702 * Possible signatures:
703 *
704 * * {@link connect}
705 * * {@link connect} for `IPC` connections.
706 * * {@link connect} for TCP connections.
707 */
708 function connect(options: NetConnectOpts, connectionListener?: () => void): Socket;
709 function connect(port: number, host?: string, connectionListener?: () => void): Socket;
710 function connect(path: string, connectionListener?: () => void): Socket;
711 /**
712 * A factory function, which creates a new {@link Socket},
713 * immediately initiates connection with `socket.connect()`,
714 * then returns the `net.Socket` that starts the connection.
715 *
716 * When the connection is established, a `'connect'` event will be emitted
717 * on the returned socket. The last parameter `connectListener`, if supplied,
718 * will be added as a listener for the `'connect'` event **once**.
719 *
720 * Possible signatures:
721 *
722 * * {@link createConnection}
723 * * {@link createConnection} for `IPC` connections.
724 * * {@link createConnection} for TCP connections.
725 *
726 * The {@link connect} function is an alias to this function.
727 */
728 function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket;
729 function createConnection(port: number, host?: string, connectionListener?: () => void): Socket;
730 function createConnection(path: string, connectionListener?: () => void): Socket;
731 /**
732 * Tests if input is an IP address. Returns `0` for invalid strings,
733 * returns `4` for IP version 4 addresses, and returns `6` for IP version 6
734 * addresses.
735 * @since v0.3.0
736 */
737 function isIP(input: string): number;
738 /**
739 * Returns `true` if input is a version 4 IP address, otherwise returns `false`.
740 * @since v0.3.0
741 */
742 function isIPv4(input: string): boolean;
743 /**
744 * Returns `true` if input is a version 6 IP address, otherwise returns `false`.
745 * @since v0.3.0
746 */
747 function isIPv6(input: string): boolean;
748 interface SocketAddressInitOptions {
749 /**
750 * The network address as either an IPv4 or IPv6 string.
751 * @default 127.0.0.1
752 */
753 address?: string | undefined;
754 /**
755 * @default `'ipv4'`
756 */
757 family?: IPVersion | undefined;
758 /**
759 * An IPv6 flow-label used only if `family` is `'ipv6'`.
760 * @default 0
761 */
762 flowlabel?: number | undefined;
763 /**
764 * An IP port.
765 * @default 0
766 */
767 port?: number | undefined;
768 }
769 /**
770 * @since v15.14.0, v14.18.0
771 */
772 class SocketAddress {
773 constructor(options: SocketAddressInitOptions);
774 /**
775 * Either \`'ipv4'\` or \`'ipv6'\`.
776 * @since v15.14.0, v14.18.0
777 */
778 readonly address: string;
779 /**
780 * Either \`'ipv4'\` or \`'ipv6'\`.
781 * @since v15.14.0, v14.18.0
782 */
783 readonly family: IPVersion;
784 /**
785 * @since v15.14.0, v14.18.0
786 */
787 readonly port: number;
788 /**
789 * @since v15.14.0, v14.18.0
790 */
791 readonly flowlabel: number;
792 }
793}
794declare module 'node:net' {
795 export * from 'net';
796}
797
\No newline at end of file