net: support TCP_KEEPINTVL and TCP_KEEPCNT in setKeepAlive

Signed-off-by: Guy Bedford <guybedford@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63825
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
Guy Bedford authored and Antoine du Hamel committed 2026-07-30 13:51:35 +02:00
1 parent e40cee5f79
commit a534b65815
6 files changed
+216 -24

No files matched your search

+3 -3
View File
@@ -3707,7 +3707,7 @@ changes:
**Default:** `false`.
* `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`].
similarly on what is done in [`socket.setKeepAlive()`][].
**Default:** `false`.
* `keepAliveInitialDelay` {number} If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
@@ -4707,7 +4707,7 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
[`server.timeout`]: #servertimeout
[`setHeader(name, value)`]: #requestsetheadername-value
[`socket.connect()`]: net.md#socketconnectoptions-connectlistener
[`socket.setKeepAlive()`]: net.md#socketsetkeepaliveenable-initialdelay
[`socket.setKeepAlive()`]: net.md#socketsetkeepalive
[`socket.setNoDelay()`]: net.md#socketsetnodelaynodelay
[`socket.setTimeout()`]: net.md#socketsettimeouttimeout-callback
[`socket.unref()`]: net.md#socketunref
@@ -4719,4 +4719,4 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
[`writable.uncork()`]: stream.md#writableuncork
[`writable.write()`]: stream.md#writablewritechunk-encoding-callback
[information event]: #event-information
[initial delay]: net.md#socketsetkeepaliveenable-initialdelay
[initial delay]: net.md#socketsetkeepaliveenable-initialdelay-interval-count
+73 -16
View File
@@ -1374,11 +1374,76 @@ added: v0.1.90
Set the encoding for the socket as a [Readable Stream][]. See
[`readable.setEncoding()`][] for more information.
### `socket.setKeepAlive([enable][, initialDelay])`
### `socket.setKeepAlive()`
Enable/disable keep-alive functionality, and optionally configure the
keepalive probe timing. Returns the socket itself.
Possible signatures:
* [`socket.setKeepAlive([options])`][`socket.setKeepAlive(options)`]
* [`socket.setKeepAlive([enable][, initialDelay][, interval][, count])`][`socket.setKeepAlive(enable)`]
Enabling keep-alive sets the initial delay before the first keepalive probe is
sent on an idle socket.
Set `initialDelay` (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting `0` for
`initialDelay` will leave the value unchanged from the default
(or previous) setting.
Set `interval` (in milliseconds) to set the delay between successive
keepalive probes once they begin (`TCP_KEEPINTVL`). Set `count` to the
number of unacknowledged probes sent before the connection is dropped
(`TCP_KEEPCNT`). Both are only applied when keep-alive is enabled.
Omitting `interval` or `count` uses the defaults of `1000` ms and `10`.
As with `initialDelay`, a non-positive `interval` or `count` leaves the
corresponding system default unchanged.
`initialDelay` and `interval` are specified in milliseconds but the
underlying socket options are configured in whole seconds; the values are
divided by `1000` and rounded down before being applied.
Enabling the keep-alive functionality will set the following socket options:
* `SO_KEEPALIVE=1`
* `TCP_KEEPIDLE=initialDelay / 1000`
* `TCP_KEEPCNT=count`
* `TCP_KEEPINTVL=interval / 1000`
On Windows versions older than build 1709, keep-alive is configured through
`SIO_KEEPALIVE_VALS`, which has no probe-count field, so `count` is ignored on
those platforms.
#### `socket.setKeepAlive([options])`
<!-- YAML
added: REPLACEME
-->
* `options` {Object}
* `enable` {boolean} **Default:** `false`
* `initialDelay` {number} **Default:** `0`
* `interval` {number} **Default:** `1000`
* `count` {number} **Default:** `10`
* Returns: {net.Socket} The socket itself.
Configure keep-alive using an options object. See [`socket.setKeepAlive()`][]
for a description of each property.
```js
socket.setKeepAlive({ enable: true, initialDelay: 1000, interval: 1000, count: 10 });
```
#### `socket.setKeepAlive([enable][, initialDelay][, interval][, count])`
<!-- YAML
added: v0.1.92
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/63825
description: Added the `interval` and `count` arguments to configure
`TCP_KEEPINTVL` and `TCP_KEEPCNT`.
- version:
- v13.12.0
- v12.17.0
@@ -1388,22 +1453,12 @@ changes:
* `enable` {boolean} **Default:** `false`
* `initialDelay` {number} **Default:** `0`
* `interval` {number} **Default:** `1000`
* `count` {number} **Default:** `10`
* Returns: {net.Socket} The socket itself.
Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.
Set `initialDelay` (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting `0` for
`initialDelay` will leave the value unchanged from the default
(or previous) setting.
Enabling the keep-alive functionality will set the following socket options:
* `SO_KEEPALIVE=1`
* `TCP_KEEPIDLE=initialDelay`
* `TCP_KEEPCNT=10`
* `TCP_KEEPINTVL=1`
Configure keep-alive using positional arguments. See
[`socket.setKeepAlive()`][] for a description of each argument.
### `socket.setNoDelay([noDelay])`
@@ -2070,7 +2125,9 @@ net.isIPv6('fhqwhgads'); // returns false
[`socket.pause()`]: #socketpause
[`socket.resume()`]: #socketresume
[`socket.setEncoding()`]: #socketsetencodingencoding
[`socket.setKeepAlive()`]: #socketsetkeepaliveenable-initialdelay
[`socket.setKeepAlive()`]: #socketsetkeepalive
[`socket.setKeepAlive(enable)`]: #socketsetkeepaliveenable-initialdelay-interval-count
[`socket.setKeepAlive(options)`]: #socketsetkeepaliveoptions
[`socket.setTimeout()`]: #socketsettimeouttimeout-callback
[`socket.setTimeout(timeout)`]: #socketsettimeouttimeout-callback
[`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode
+2
View File
@@ -103,6 +103,8 @@ module.exports = {
kSetNoDelay: Symbol('kSetNoDelay'),
kSetKeepAlive: Symbol('kSetKeepAlive'),
kSetKeepAliveInitialDelay: Symbol('kSetKeepAliveInitialDelay'),
kSetKeepAliveInterval: Symbol('kSetKeepAliveInterval'),
kSetKeepAliveCount: Symbol('kSetKeepAliveCount'),
isIP,
isIPv4,
isIPv6,
+24 -4
View File
@@ -51,6 +51,8 @@ const {
kSetNoDelay,
kSetKeepAlive,
kSetKeepAliveInitialDelay,
kSetKeepAliveInterval,
kSetKeepAliveCount,
isIP,
isIPv4,
isIPv6,
@@ -630,13 +632,25 @@ Socket.prototype.setNoDelay = function(enable) {
};
Socket.prototype.setKeepAlive = function(enable, initialDelayMsecs) {
Socket.prototype.setKeepAlive = function(enable, initialDelayMsecs,
intervalMsecs, count) {
if (enable !== null && typeof enable === 'object') {
const options = enable;
enable = options.enable;
initialDelayMsecs = options.initialDelay;
intervalMsecs = options.interval;
count = options.count;
}
enable = Boolean(enable);
const initialDelay = ~~(initialDelayMsecs / 1000);
const interval = intervalMsecs === undefined ?
undefined : ~~(intervalMsecs / 1000);
if (!this._handle) {
this[kSetKeepAlive] = enable;
this[kSetKeepAliveInitialDelay] = initialDelay;
this[kSetKeepAliveInterval] = interval;
this[kSetKeepAliveCount] = count;
return this;
}
@@ -647,12 +661,16 @@ Socket.prototype.setKeepAlive = function(enable, initialDelayMsecs) {
if (enable !== this[kSetKeepAlive] ||
(
enable &&
this[kSetKeepAliveInitialDelay] !== initialDelay
(this[kSetKeepAliveInitialDelay] !== initialDelay ||
this[kSetKeepAliveInterval] !== interval ||
this[kSetKeepAliveCount] !== count)
)
) {
this[kSetKeepAlive] = enable;
this[kSetKeepAliveInitialDelay] = initialDelay;
this._handle.setKeepAlive(enable, initialDelay);
this[kSetKeepAliveInterval] = interval;
this[kSetKeepAliveCount] = count;
this._handle.setKeepAlive(enable, initialDelay, interval, count);
}
return this;
@@ -1676,7 +1694,9 @@ function afterConnect(status, handle, req, readable, writable) {
}
if (self[kSetKeepAlive] && self._handle.setKeepAlive) {
self._handle.setKeepAlive(true, self[kSetKeepAliveInitialDelay]);
self._handle.setKeepAlive(true, self[kSetKeepAliveInitialDelay],
self[kSetKeepAliveInterval],
self[kSetKeepAliveCount]);
}
if (self[kSetTOS] !== undefined && self._handle.setTypeOfService) {
+8 -1
View File
@@ -208,7 +208,14 @@ void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
int enable;
if (!args[0]->Int32Value(env->context()).To(&enable)) return;
unsigned int delay = static_cast<unsigned int>(args[1].As<Uint32>()->Value());
int err = uv_tcp_keepalive(&wrap->handle_, enable, delay);
// interval and count are optional. Fall back to the libuv defaults
// (1 second, 10 probes) when they are not provided so that callers using
// the legacy two-argument form of this handle method keep working.
unsigned int interval = 1;
unsigned int count = 10;
if (args[2]->IsUint32()) interval = args[2].As<Uint32>()->Value();
if (args[3]->IsUint32()) count = args[3].As<Uint32>()->Value();
int err = uv_tcp_keepalive_ex(&wrap->handle_, enable, delay, interval, count);
args.GetReturnValue().Set(err);
}
@@ -0,0 +1,106 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
// Verifies that setKeepAlive() forwards the keepalive probe interval
// (TCP_KEEPINTVL) and probe count (TCP_KEEPCNT) to the handle. The interval is
// converted from milliseconds to whole seconds, mirroring the initialDelay
// handling and uv_tcp_keepalive_ex().
// Explicit setKeepAlive(enable, initialDelay, interval, count) forwards all
// four values, converting milliseconds to seconds for the delays.
{
const server = net.createServer();
server.listen(0, common.mustCall(() => {
const client = net.connect(
{ port: server.address().port },
common.mustCall(() => {
client._handle.setKeepAlive = common.mustCall(
(enable, delay, interval, count) => {
assert.strictEqual(enable, true);
assert.strictEqual(delay, 5);
assert.strictEqual(interval, 10);
assert.strictEqual(count, 9);
});
client.setKeepAlive(true, 5000, 10000, 9);
client.end();
}));
client.on('end', common.mustCall(() => server.close()));
}));
}
// Omitting interval/count passes undefined through; the handle applies the
// libuv defaults (1s interval, 10 probes).
{
const server = net.createServer();
server.listen(0, common.mustCall(() => {
const client = net.connect(
{ port: server.address().port },
common.mustCall(() => {
client._handle.setKeepAlive = common.mustCall(
(enable, delay, interval, count) => {
assert.strictEqual(enable, true);
assert.strictEqual(delay, 5);
assert.strictEqual(interval, undefined);
assert.strictEqual(count, undefined);
});
client.setKeepAlive(true, 5000);
client.end();
}));
client.on('end', common.mustCall(() => server.close()));
}));
}
// An options object as the first argument is equivalent to the positional
// form, forwarding enable/initialDelay/interval/count to the handle.
{
const server = net.createServer();
server.listen(0, common.mustCall(() => {
const client = net.connect(
{ port: server.address().port },
common.mustCall(() => {
client._handle.setKeepAlive = common.mustCall(
(enable, delay, interval, count) => {
assert.strictEqual(enable, true);
assert.strictEqual(delay, 5);
assert.strictEqual(interval, 10);
assert.strictEqual(count, 9);
});
client.setKeepAlive({
enable: true,
initialDelay: 5000,
interval: 10000,
count: 9,
});
client.end();
}));
client.on('end', common.mustCall(() => server.close()));
}));
}
// Omitted options properties behave like omitted positional arguments.
{
const server = net.createServer();
server.listen(0, common.mustCall(() => {
const client = net.connect(
{ port: server.address().port },
common.mustCall(() => {
client._handle.setKeepAlive = common.mustCall(
(enable, delay, interval, count) => {
assert.strictEqual(enable, true);
assert.strictEqual(delay, 5);
assert.strictEqual(interval, undefined);
assert.strictEqual(count, undefined);
});
client.setKeepAlive({ enable: true, initialDelay: 5000 });
client.end();
}));
client.on('end', common.mustCall(() => server.close()));
}));
}