Skip to content

Commit 8568c23

Browse files
committed
Initial commit checks status of a specified port.
0 parents  commit 8568c23

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

example/portscan.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var portscanner = require('../lib/portscanner.js')
2+
3+
portscanner.checkPortStatus('3000', 'localhost', function(error, status) {
4+
console.log(status)
5+
})
6+
7+
portscanner.findAnAvailablePort(3000, 3010, 'localhost', function(error, port) {
8+
console.log('AVAILABLE PORT AT ' + port)
9+
})
10+
11+
setTimeout(function() { }, 10000)
12+

lib/portscanner.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
 (0)