|
| 1 | +var net = require('net') |
| 2 | + , Socket = net.Socket |
| 3 | + |
| 4 | +var portscanner = exports |
| 5 | + |
| 6 | +portscanner.findAnAvailablePort = function(startPort, endPort, host, callback) { |
| 7 | + var that = this |
| 8 | + var foundAvailablePort = false |
| 9 | + var numberOfPortsChecked = 0 |
| 10 | + |
| 11 | + var check = function(port) { |
| 12 | + that.checkPortStatus(port, host, function(error, status) { |
| 13 | + numberOfPortsChecked++ |
| 14 | + // Only callback once |
| 15 | + if (foundAvailablePort === false) { |
| 16 | + if (error) { |
| 17 | + foundAvailablePort = true |
| 18 | + callback(error) |
| 19 | + } |
| 20 | + else { |
| 21 | + if (status === 'open') { |
| 22 | + foundAvailablePort = true |
| 23 | + callback(null, port) |
| 24 | + } |
| 25 | + // All port checks have returned unavailable |
| 26 | + else if (numberOfPortsChecked === (endPort - startPort + 1)) { |
| 27 | + callback(null, false) |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + }) |
| 32 | + } |
| 33 | + |
| 34 | + for (var port = startPort; port <= endPort; port++) { |
| 35 | + check(port) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +portscanner.checkPortStatus = function(port, host, callback) { |
| 40 | + var socket = new Socket() |
| 41 | + |
| 42 | + // Socket connection established, port is open |
| 43 | + socket.on('connect', function() { |
| 44 | + console.log('ON CONNECT') |
| 45 | + socket.end() |
| 46 | + callback(null, 'open') |
| 47 | + }) |
| 48 | + |
| 49 | + // If no response, assume port is not listening |
| 50 | + socket.setTimeout(400) |
| 51 | + socket.on('timeout', function() { |
| 52 | + console.log('ON TIMEOUT') |
| 53 | + socket.end() |
| 54 | + callback(null, 'closed') |
| 55 | + }) |
| 56 | + |
| 57 | + // Assuming the port is not open if an error. May need to refine based on |
| 58 | + // exception |
| 59 | + socket.on('error', function(exception) { |
| 60 | + console.log('ON ERROR') |
| 61 | + //console.log(exception) |
| 62 | + socket.end() |
| 63 | + callback(null, 'closed') |
| 64 | + }) |
| 65 | + |
| 66 | + host = host || 'localhost' |
| 67 | + socket.connect(port, host) |
| 68 | +} |
| 69 | + |
0 commit comments