-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 5fe94a0
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/** | ||
* LICENSE MIT | ||
* (C) Daniel Zelisko | ||
* http://github.com/danielzzz/node-portchecker | ||
* | ||
* a simple tcp port checker | ||
* Use it for checking if a service is up or to find available ports on a machine | ||
*/ | ||
|
||
var sys = require('sys'); | ||
var net = require('net'); | ||
|
||
|
||
|
||
|
||
// start port, last port, host, callback | ||
exports.getFirstAvailable = function (p, m, host, callback) { | ||
var notFree = false; | ||
var conn = net.createConnection(p, host); | ||
var onClose = function() { | ||
if (notFree) {conn.connect(p); notFree = false; return;} | ||
delete conn; | ||
callback(p, host); | ||
}; | ||
|
||
var onOpen = function() { | ||
notFree = true; | ||
console.log(host+":"+p+" is taken"); | ||
|
||
//not found | ||
if (p >= m) { | ||
conn.removeListener('close', onClose); | ||
delete conn; | ||
callback(-1, host); | ||
|
||
} | ||
|
||
p++; | ||
conn.end(); | ||
}; | ||
|
||
conn.on('close', onClose); | ||
conn.on('error', function() {}); | ||
|
||
conn.on('connect', onOpen); | ||
|
||
|
||
} | ||
|
||
//usage example: find first available port between 2000 and 2100 on localhost | ||
this.getFirstAvailable(80, 8090, 'localhost', function(p, host) { console.log(host+":"+p+" is free");}); |