Skip to content

Commit 604880b

Browse files
committed
server: support binding to specific hostname
Fixes webtorrent#68
1 parent 8e7a434 commit 604880b

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ server.on('listening', function () {
143143
})
144144

145145
// start tracker server listening! Use 0 to listen on a random free port.
146-
server.listen(port)
146+
server.listen(port, hostname, onlistening)
147147

148148
// listen for individual tracker messages from peers:
149149

server.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,23 +99,24 @@ Server.prototype._onError = function (err) {
9999
self.emit('error', err)
100100
}
101101

102-
Server.prototype.listen = function (port, onlistening) {
102+
Server.prototype.listen = function (/* port, hostname, onlistening */) {
103103
var self = this
104-
if (typeof port === 'function') {
105-
onlistening = port
106-
port = undefined
107-
}
108-
if (!port) port = 0
104+
105+
var lastArg = arguments[arguments.length - 1]
106+
if (typeof lastArg === 'function') self.once('listening', lastArg)
107+
108+
var port = toNumber(arguments[0]) || arguments[0] || 0
109+
var hostname = typeof arguments[1] !== 'function' ? arguments[1] : undefined
110+
109111
if (self.listening) throw new Error('server already listening')
110-
debug('listen %o', port)
111112

112-
if (onlistening) self.once('listening', onlistening)
113+
debug('listen %o %s', port, hostname)
113114

114115
// ATTENTION:
115116
// binding to :: only receives IPv4 connections if the bindv6only
116117
// sysctl is set 0, which is the default on many operating systems.
117-
self.http && self.http.listen(port.http || port, '::')
118-
self.udp && self.udp.bind(port.udp || port)
118+
self.http && self.http.listen(port.http || port, hostname || '::')
119+
self.udp && self.udp.bind(port.udp || port, hostname)
119120
}
120121

121122
Server.prototype.close = function (cb) {
@@ -485,3 +486,5 @@ Server.prototype._onWebSocketError = function (socket, err) {
485486
self.emit('warning', err)
486487
self._onWebSocketClose(socket)
487488
}
489+
490+
function toNumber (x) { return (x = Number(x)) >= 0 ? x : false }

0 commit comments

Comments
 (0)