Permalink
Browse files

Checks range of ports one at a time.

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...
1 parent fe97267 commit c81ae8d6e47d060a6f18f3373557e010db8ffcf5 @baalexander committed Nov 2, 2011
Showing with 35 additions and 21 deletions.
  1. +1 −0 .gitignore
  2. +33 −20 lib/portscanner.js
  3. +1 −1 package.json
View
@@ -0,0 +1 @@
+node_modules
View
@@ -1,5 +1,6 @@
var net = require('net')
, Socket = net.Socket
+ , async = require('async')
var portscanner = exports
@@ -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)
+ }
+ })
}
View
@@ -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" :

0 comments on commit c81ae8d

Please sign in to comment.