This repository was archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnetutil.js
66 lines (53 loc) · 1.6 KB
/
netutil.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var net = require("net");
var exec = require("child_process").exec;
exports.findFreePort = function(start, end, pivot, hostname, callback) {
if (!callback)
return exports.findFreePort(start, end, Math.floor(Math.random() * (end-start)) + start, pivot, hostname);
var port = pivot;
asyncRepeat(function(next, done) {
var stream = net.createConnection(port, hostname);
stream.on("connect", function() {
stream.destroy();
port++;
if (port > end)
port = start;
if (port == pivot)
done("Could not find free port.");
next();
});
stream.on("error", function() {
done();
});
}, function(err) {
callback(err, port);
});
};
exports.isPortOpen = function(hostname, port, timeout, callback) {
var stream = net.createConnection(port, hostname);
stream.on("connect", function() {
clearTimeout(id);
stream.destroy();
callback(true);
});
stream.on("error", function() {
clearTimeout(id);
stream.destroy();
callback(false);
});
var id = setTimeout(function() {
stream.destroy();
callback(false);
}, timeout || 1000);
};
exports.getHostName = function(callback) {
exec("hostname", function (error, stdout, stderr) {
if (error)
return callback(stderr);
callback(null, stdout.toString().split("\n")[0]);
});
};
function asyncRepeat(callback, onDone) {
callback(function() {
asyncRepeat(callback, onDone);
}, onDone);
}