diff --git a/lib/network.js b/lib/network.js index b74044a..d78ac1d 100644 --- a/lib/network.js +++ b/lib/network.js @@ -1,6 +1,7 @@ var dgram = require('dgram'), crypto = require('crypto'), os = require('os'), + broadcastAddress = require("broadcast-address"), EventEmitter = require('events').EventEmitter, util = require('util'), uuid = require('uuid/v4'), @@ -9,8 +10,8 @@ var dgram = require('dgram'), var procUuid = uuid(); var hostName = process.env.DISCOVERY_HOSTNAME || os.hostname(); -module.exports = Network; - +module.exports = Network; + function Network (options) { if (!(this instanceof Network)) { return new Network(options, callback); @@ -96,7 +97,29 @@ Network.prototype.start = function (callback) { self.socket.setBroadcast(true); //TODO: get the default broadcast address from os.networkInterfaces() (not currently returned) - self.destination = [self.broadcast || "255.255.255.255"]; + + if (self.broadcast) { + self.destination = Array.isArray( self.broadcast) ? self.broadcast.slice(0) : [self.broadcast]; + } else { + self.destination = []; + var networkInterfaces = os.networkInterfaces(); + for (var interfaceName in networkInterfaces) { + if (!networkInterfaces.hasOwnProperty(interfaceName)) { + continue; + } + for (var i = 0; i < networkInterfaces[interfaceName].length; i++) { + var iface = networkInterfaces[interfaceName][i]; + if (iface.internal || iface.family !== "IPv4") { + continue; + } + + var broadcast = broadcastAddress(interfaceName, iface.address); + if (broadcast) { + self.destination.push(broadcast); + } + } + } + } } else { try { @@ -149,7 +172,7 @@ Network.prototype.send = function (event) { } var msg = Buffer.from(contents); - + self.destination.forEach(function (destination) { self.socket.send( msg diff --git a/package.json b/package.json index b9edeca..d7bf88b 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "node": ">=0.4.1 <0.5.0 || >=0.6.9" }, "dependencies": { + "broadcast-address": "^1.0.2", "uuid": "^3.3.2" }, "bugs": {