Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
danielzzz committed Sep 29, 2010
0 parents commit 5fe94a0
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
Empty file added README
Empty file.
51 changes: 51 additions & 0 deletions portchecker.js
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");});

0 comments on commit 5fe94a0

Please sign in to comment.