Created
September 4, 2014 12:57
-
-
Save rosterloh/41a2f428077aeab547b9 to your computer and use it in GitHub Desktop.
Node.js Port Scan Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("\n").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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment