var child = require("child_process");
var async = require("async");
var net = require("net");
var os = require("os");
function scan(port, cb){
var hosts = {};
var result = [];
async.series([
function scan(next, c){
if(c == 1){
next(); return;
}
// scan twice because arp sometimes does not list all hosts on first time
child.exec("arp -n | awk '{print $1}' | tail -n+2", function(err, res){
if(err) cb(err);
else {
var list = res.split("
").filter(function(x){return x !== "";});
list.map(function(x){
hosts[x] = x;
});
}
scan(next, 1);
});
},
function(next){
// if you want to scan local addresses as well
var ifs = os.networkInterfaces();
Object.keys(ifs).map(function(x){
hosts[((ifs[x][0])||{}).address] = true;
});
// do the scan
async.each(Object.keys(hosts), function(x, next){
var s = new net.Socket();
s.setTimeout(1500, function(){s.destroy(); next();});
s.on("error", function(){
s.destroy();
next();
});
s.connect(port, x, function(){
result.push(x);
s.destroy();
next();
});
}, function(){
next();
});
}
], function(){
cb(null, result);
});
}
scan(80, function(err, hosts){
if(err){
console.error(err);
} else {
console.log("Found hosts: "+hosts);
}
});