Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #3 from MiguelMadero/master

Network utility for port sniffing needed by geddy
  • Loading branch information...
commit 78c928b573020b33e8503b1111421a4660258ba6 2 parents 9b9086c + 3974012
@larzconwell larzconwell authored
Showing with 90 additions and 0 deletions.
  1. +2 −0  lib/index.js
  2. +47 −0 lib/network.js
  3. +41 −0 test/network.js
View
2  lib/index.js
@@ -29,6 +29,7 @@ var utils = {}
, date = require('./date')
, request = require('./request')
, log = require('./log')
+ , network = require('./network')
// Third-party -- remove this if possible
, inflection = require('./inflection')
// Constructors
@@ -48,6 +49,7 @@ utils.object = object;
utils.date = date;
utils.request = request;
utils.log = log;
+utils.network = network;
utils.inflection = inflection;
utils.SortedCollection = SortedCollection;
utils.EventBuffer = EventBuffer;
View
47 lib/network.js
@@ -0,0 +1,47 @@
+var network
+ , net = require('net');
+
+/**
+ @name network
+ @namespace network
+*/
+network = new (function () {
+ /**
+ @name network#isPortOpen
+ @public
+ @function
+ @description Checks if the given port in the given host is open
+ @param {Number} port number
+ @param {String} host
+ @param {Function} callback Callback function -- should be in the format of function(err, result) {}
+ */
+ this.isPortOpen = function (port, host, callback) {
+ var isOpen = false
+ , connection
+ , error;
+
+ connection = net.createConnection(port, host, function () {
+ isOpen = true;
+ connection.end();
+ });
+
+ connection.on('error', function (err) {
+ // We ignore 'ECONNREFUSED' as it simply indicates the port isn't open. Anything else is reported
+ if(err.code !== 'ECONNREFUSED') {
+ error = err;
+ }
+ // the socket emits 'close' after 'error'. No need to do anything here
+ })
+
+ connection.setTimeout(400, function () {
+ connection.end();
+ });
+
+ connection.on('close', function (had_error) {
+ callback(error, isOpen);
+ });
+ };
+
+})();
+
+module.exports = network;
View
41 test/network.js
@@ -0,0 +1,41 @@
+var assert = require('assert')
+ , sys = require('sys')
+ , net = require('net')
+ , network = require('../lib/network')
+ , tests;
+
+tests = {
+
+ 'test a port is open': function (next) {
+ var expected = false
+ , port = 49152;
+
+ network.isPortOpen(port, null, function (err, isOpen) {
+ assert.ifError(err);
+ assert.equal(expected, isOpen);
+
+ next();
+ });
+
+ }
+
+, 'test a port is closed': function (next) {
+
+ var expected = true
+ , port = 49153
+ , server = net.createServer();
+
+ server.listen(port, function () {
+ network.isPortOpen(port, null, function (err, isOpen) {
+ assert.ifError(err);
+ assert.equal(expected, isOpen);
+
+ server.close(function () {
+ next();
+ });
+ });
+ });
+ }
+}
+
+module.exports = tests;
Please sign in to comment.
Something went wrong with that request. Please try again.