Skip to content

Commit

Permalink
Initial commit checks status of a specified port.
Browse files Browse the repository at this point in the history
  • Loading branch information
baalexander committed Aug 11, 2011
0 parents commit 8568c23
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
12 changes: 12 additions & 0 deletions example/portscan.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var portscanner = require('../lib/portscanner.js')

portscanner.checkPortStatus('3000', 'localhost', function(error, status) {
console.log(status)
})

portscanner.findAnAvailablePort(3000, 3010, 'localhost', function(error, port) {
console.log('AVAILABLE PORT AT ' + port)
})

setTimeout(function() { }, 10000)

69 changes: 69 additions & 0 deletions lib/portscanner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
var net = require('net')
, Socket = net.Socket

var portscanner = exports

portscanner.findAnAvailablePort = function(startPort, endPort, host, callback) {
var that = this
var foundAvailablePort = false
var numberOfPortsChecked = 0

var check = function(port) {
that.checkPortStatus(port, host, function(error, status) {
numberOfPortsChecked++
// Only callback once
if (foundAvailablePort === false) {
if (error) {
foundAvailablePort = true
callback(error)
}
else {
if (status === 'open') {
foundAvailablePort = true
callback(null, port)
}
// All port checks have returned unavailable
else if (numberOfPortsChecked === (endPort - startPort + 1)) {
callback(null, false)
}
}
}
})
}

for (var port = startPort; port <= endPort; port++) {
check(port)
}
}

portscanner.checkPortStatus = function(port, host, callback) {
var socket = new Socket()

// Socket connection established, port is open
socket.on('connect', function() {
console.log('ON CONNECT')
socket.end()
callback(null, 'open')
})

// If no response, assume port is not listening
socket.setTimeout(400)
socket.on('timeout', function() {
console.log('ON TIMEOUT')
socket.end()
callback(null, 'closed')
})

// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function(exception) {
console.log('ON ERROR')
//console.log(exception)
socket.end()
callback(null, 'closed')
})

host = host || 'localhost'
socket.connect(port, host)
}

0 comments on commit 8568c23

Please sign in to comment.