node/test/sequential/test-dgram-implicit-bind-failure.js
Ruben Bridgewater 1c12dd6347
dgram: skip dns.lookup() for literal IP addresses
Every unconnected send(), and the implicit bind on first send,
resolved the destination through dns.lookup() even when it was
already a literal IP. The address resolves to itself, so the call is
redundant, and tools that instrument dns.lookup() record a lookup for
every datagram sent to an IP.

Skip the resolver for a literal IP of the socket's family and report
it on the next tick, keeping dns.lookup()'s asynchronous contract. A
custom lookup function is still consulted for every address.

Refs: https://github.com/DataDog/dd-trace-js/issues/2984
Signed-off-by: Ruben Bridgewater <ruben@bridgewater.de>
PR-URL: https://github.com/nodejs/node/pull/64133
Reviewed-By: Bryan English <bryan@bryanenglish.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-06-30 13:07:49 +00:00

41 lines
1.4 KiB
JavaScript

// Flags: --expose-internals
'use strict';
const common = require('../common');
const assert = require('assert');
const EventEmitter = require('events');
const dgram = require('dgram');
const { kStateSymbol } = require('internal/dgram');
const mockError = new Error('fake DNS');
const socket = dgram.createSocket('udp4');
// Fail the implicit bind by making the handle's address resolution fail. A
// literal bind address is not passed to dns.lookup(), so patching dns.lookup()
// would not be observed here.
socket[kStateSymbol].handle.lookup = function(address, callback) {
process.nextTick(() => { callback(mockError); });
};
socket.on(EventEmitter.errorMonitor, common.mustCall((err) => {
// The bind should fail since the lookup is monkey patched. At that point in
// time, the send queue should be populated with the send() operation.
assert.strictEqual(err, mockError);
assert(Array.isArray(socket[kStateSymbol].queue));
assert.strictEqual(socket[kStateSymbol].queue.length, 1);
}, 3));
socket.on('error', common.mustCall((err) => {
assert.strictEqual(err, mockError);
assert.strictEqual(socket[kStateSymbol].queue, undefined);
}, 3));
// Initiate a few send() operations, which will fail.
socket.send('foobar', common.PORT, 'localhost');
process.nextTick(() => {
socket.send('foobar', common.PORT, 'localhost');
});
setImmediate(() => {
socket.send('foobar', common.PORT, 'localhost');
});