Skip to content

Commit 4abe2fa

Browse files
committed
net: add lookup option to Socket.prototype.connect
Allows customization of the lookup function used when Socket.prototype.connect is called using a hostname. PR-URL: #1505 Reviewed-By: Chris Dickinson <[email protected]> Reviewed-By: Yosuke Furukawa <[email protected]>
1 parent 1bef717 commit 4abe2fa

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

doc/api/net.markdown

+2
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,8 @@ For TCP sockets, `options` argument should be an object which specifies:
355355
- `localPort`: Local port to bind to for network connections.
356356

357357
- `family` : Version of IP stack. Defaults to `4`.
358+
359+
- `lookup` : Custom lookup function. Defaults to `dns.lookup`.
358360

359361
For local domain sockets, `options` argument should be an object which
360362
specifies:

lib/net.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,9 @@ function lookupAndConnect(self, options) {
916916
return;
917917
}
918918

919+
if (options.lookup && typeof options.lookup !== 'function')
920+
throw new TypeError('options.lookup should be a function.');
921+
919922
var dnsopts = {
920923
family: options.family,
921924
hints: 0
@@ -927,7 +930,8 @@ function lookupAndConnect(self, options) {
927930
debug('connect: find host ' + host);
928931
debug('connect: dns options ' + dnsopts);
929932
self._host = host;
930-
dns.lookup(host, dnsopts, function(err, ip, addressType) {
933+
var lookup = options.lookup || dns.lookup;
934+
lookup(host, dnsopts, function(err, ip, addressType) {
931935
self.emit('lookup', err, ip, addressType);
932936

933937
// It's possible we were destroyed while looking this up.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
var net = require('net');
4+
var dns = require('dns');
5+
var ok = false;
6+
7+
function check(addressType, cb) {
8+
var server = net.createServer(function(client) {
9+
client.end();
10+
server.close();
11+
cb && cb();
12+
});
13+
14+
var address = addressType === 4 ? '127.0.0.1' : '::1';
15+
server.listen(common.PORT, address, function() {
16+
net.connect({
17+
port: common.PORT,
18+
host: 'localhost',
19+
lookup: lookup
20+
}).on('lookup', function(err, ip, type) {
21+
assert.equal(err, null);
22+
assert.equal(ip, address);
23+
assert.equal(type, addressType);
24+
ok = true;
25+
});
26+
});
27+
28+
function lookup(host, dnsopts, cb) {
29+
dnsopts.family = addressType;
30+
dns.lookup(host, dnsopts, cb);
31+
}
32+
}
33+
34+
check(4, function() {
35+
common.hasIPv6 && check(6);
36+
});
37+
38+
process.on('exit', function() {
39+
assert.ok(ok);
40+
});

0 commit comments

Comments
 (0)