From 5042138741234a33b0c63129513fefa62bb5c02e Mon Sep 17 00:00:00 2001 From: somec Date: Sun, 4 Mar 2018 00:36:46 +0100 Subject: [PATCH] Added binding of socket to address and port The default behavior is to bind the socket to all interfaces on a random port. On a multi-homed node it sometimes is preferred if the socket was only bound to a specific address. The underlying dgram socket from node has the necessary support for binding to an address, if that address is specified while binding. Added options to new Session(options) * sourceAddress: The IP address to bind the socket to, and where requests are coming from. Must be an IP address on the node, if specified. Default is to bind to all interfaces. * sourcePort: The UDP port number to bind the socket to, and where requests are coming from. Default: 0 (random). --- README.md | 5 +++++ lib/snmp.js | 13 +++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 89878ca..1299227 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,11 @@ on each `get`, `getAll`, etc. between each). A backoff can be implemented by timeouts along the lines of `[ 1000, 2000, 4000, 8000 ]`. Retransmissions can be disabled by using only a single timeout value: `[ 5000 ]`. + - `sourceAddress`: The IP address to bind the socket to, and where requests + are coming from. Must be an IP address on the node, if specified. + Default is to bind to all interfaces. + - `sourcePort`: The UDP port number to bind the socket to, and where requests + are coming from. Default: `0` (random). ### VarBind objects diff --git a/lib/snmp.js b/lib/snmp.js index 707ed06..ca661d2 100644 --- a/lib/snmp.js +++ b/lib/snmp.js @@ -485,10 +485,19 @@ function Session(options) { // If exclusive is false (default), then cluster workers will use the same underlying handle, // allowing connection handling duties to be shared. // When exclusive is true, the handle is not shared, and attempted port sharing results in an error. - self.socket.bind({ + var bindOptions = { port: 0, //get a random port automatically exclusive: true // you should not share the same port, otherwise yours packages will be screwed up between workers - }); + }; + if (self.options.sourceAddress) { + // Support binding to specific source address (wanted on multi-homed nodes) + bindOptions.address = self.options.sourceAddress; + } + if (self.options.sourcePort) { + // Support binding to specific source port + bindOptions.port = self.options.sourcePort; + } + self.socket.bind(bindOptions); } // We inherit from EventEmitter so that we can emit error events