Skip to content

Commit

Permalink
Merge pull request #7 from EndangeredMassa/smassa/timeout
Browse files Browse the repository at this point in the history
Better timeout handling for checkPortStatus
  • Loading branch information
baalexander committed Oct 17, 2013
2 parents 3817691 + 16d0db3 commit 8f5559b
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions lib/portscanner.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,29 @@ portscanner.findAPortNotInUse = function(startPort, endPort, host, callback) {
/**
* Checks the status of an individual port.
*
* @param {Number} port - Port to check status on.
* @param {String} host - Where to scan. Defaults to 'localhost'.
* @param {Function} callback - function (error, port) { ... }
* - {Object|null} error - Any errors that occurred while port scanning.
* - {String} status - 'open' if the port is in use.
* 'closed' if the port is available.
* @param {Number} port - Port to check status on.
* @param {String|Object} options - host or options
* - {String} host - Host of where to scan. Defaults to 'localhost'.
* - {Object} options
* - {String} host - Host of where to scan. Defaults to 'localhost'.
* - {Number} timeout - Connection timeout. Defaults to 400ms.
* @param {Function} callback - function (error, port) { ... }
* - {Object|null} error - Any errors that occurred while port scanning.
* - {String} status - 'open' if the port is in use.
* 'closed' if the port is available.
*/
portscanner.checkPortStatus = function(port, host, callback) {
host = host || 'localhost'
portscanner.checkPortStatus = function(port, options, callback) {
if (typeof options === 'string') {
// Assume this param is the host option
options = {host: options}
}

var host = options.host || 'localhost'
var timeout = options.timeout || 400

var socket = new Socket()
, status = null
, error = null

// Socket connection established, port is open
socket.on('connect', function() {
Expand All @@ -64,21 +76,24 @@ portscanner.checkPortStatus = function(port, host, callback) {
})

// If no response, assume port is not listening
socket.setTimeout(400)
socket.setTimeout(timeout)
socket.on('timeout', function() {
status = 'closed'
error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
socket.destroy()
})

// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function(exception) {
error = exception
status = 'closed'
})

// Return after the socket has closed
socket.on('close', function(exception) {
callback(null, status)
if (exception) error = exception
callback(error, status)
})

socket.connect(port, host)
Expand Down

0 comments on commit 8f5559b

Please sign in to comment.