Permalink
Browse files

Adds a network utility with a function to detect if a port is open

  • Loading branch information...
1 parent 9b9086c commit 300aa3ae8828075065b43edb1bebe98314f1ac9d @MiguelMadero MiguelMadero committed Oct 9, 2012
Showing with 44 additions and 0 deletions.
  1. +2 −0 lib/index.js
  2. +42 −0 lib/network.js
View
@@ -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
@@ -0,0 +1,42 @@
+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 Defaults to null if not given
+ @param {Function} callback
+ */
+ this.isPortOpen = function (port, host, callback) {
+ var isOpen = false
+ , conn = net.createConnection(port, host)
+ , timeoutId = setTimeout(function () { onClose(); }, timeout)
+ , timeout = 400;
+
+ var onClose = function () {
+ clearTimeout(timeoutId);
+ delete conn;
+ callback(isOpen, port, host);
+ };
+
+ var onOpen = function () {
+ isOpen = true;
+ conn.end();
+ };
+
+ conn.on('close', onClose);
+ conn.on('error', function() { conn.end(); });
+ conn.on('connect', onOpen);
+ };
+
+})();
+
+module.exports = network;

0 comments on commit 300aa3a

Please sign in to comment.