Skip to content

Commit

Permalink
Checks range of ports one at a time.
Browse files Browse the repository at this point in the history
Uses the [async](https://github.com/caolan/async) library to conveniently check
each port serially. This may be slower, but prevents errors related to too many
open socket connections.

See Issue #2.
  • Loading branch information
baalexander committed Nov 2, 2011
1 parent fe97267 commit c81ae8d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 21 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
53 changes: 33 additions & 20 deletions lib/portscanner.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var net = require('net')
, Socket = net.Socket
, async = require('async')

var portscanner = exports

Expand Down Expand Up @@ -88,32 +89,44 @@ function findAPortWithStatus(status, startPort, endPort, host, callback) {
endPort = endPort || 65535
var foundPort = false
var numberOfPortsChecked = 0
var port = startPort

var check = function(port) {
// Returns true if a port with matching status has been found or if checked
// the entire range of ports
var hasFoundPort = function() {
return foundPort || numberOfPortsChecked === (endPort - startPort + 1)
}

// Checks the status of the port
var checkNextPort = function(callback) {
portscanner.checkPortStatus(port, host, function(error, statusOfPort) {
numberOfPortsChecked++
// Only callback once
if (foundPort === false) {
if (error) {
foundPort = true
callback(error)
}
else {
if (statusOfPort === status) {
foundPort = true
callback(null, port)
}
// All port checks have returned unavailable
else if (numberOfPortsChecked === (endPort - startPort + 1)) {
callback(null, false)
}
}
if (error) {
callback(error)
}
else if (statusOfPort === status) {
foundPort = true
callback(null, port)
}
else {
port++
callback(null, false)
}
})
}

for (var port = startPort; port <= endPort && foundPort === false; port++) {
check(port)
}
// Check the status of each port until one with a matching status has been
// found or the range of ports has been exhausted
async.until(hasFoundPort, checkNextPort, function(error) {
if (error) {
callback(error)
}
else if (foundPort) {
callback(null, port)
}
else {
callback(null, false)
}
})
}

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
, "bugs" : { "web" : "https://github.com/baalexander/node-portscanner/issues" }
, "directories" : { "lib" : "./lib" }
, "main" : "./lib/portscanner.js"
, "dependencies" : { }
, "dependencies" : { "async" : "0.1.15" }
, "devDependencies" : { }
, "engines" : { "node" : ">=0.4", "npm" : ">=1.0.0" }
, "licenses" :
Expand Down

0 comments on commit c81ae8d

Please sign in to comment.