2019-09-23 17:39:32 +02:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const multiaddr = require('multiaddr')
|
2020-02-13 16:22:12 +01:00
|
|
|
const errCode = require('err-code')
|
2019-09-23 17:39:32 +02:00
|
|
|
const { Address4, Address6 } = require('ip-address')
|
|
|
|
|
2020-02-13 16:22:12 +01:00
|
|
|
const errors = {
|
|
|
|
ERR_INVALID_IP_PARAMETER: 'ERR_INVALID_IP_PARAMETER',
|
|
|
|
ERR_INVALID_PORT_PARAMETER: 'ERR_INVALID_PORT_PARAMETER',
|
|
|
|
ERR_INVALID_IP: 'ERR_INVALID_IP'
|
|
|
|
}
|
|
|
|
|
2020-10-07 15:01:44 +02:00
|
|
|
/**
|
|
|
|
* Transform an IP, Port pair into a multiaddr
|
|
|
|
*
|
|
|
|
* @param {string} ip
|
|
|
|
* @param {number|string} port
|
|
|
|
*/
|
|
|
|
function ipPortToMultiaddr (ip, port) {
|
2019-09-23 17:39:32 +02:00
|
|
|
if (typeof ip !== 'string') {
|
2020-02-13 16:22:12 +01:00
|
|
|
throw errCode(new Error(`invalid ip provided: ${ip}`), errors.ERR_INVALID_IP_PARAMETER)
|
2019-09-23 17:39:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
port = parseInt(port)
|
|
|
|
|
|
|
|
if (isNaN(port)) {
|
2020-02-13 16:22:12 +01:00
|
|
|
throw errCode(new Error(`invalid port provided: ${port}`), errors.ERR_INVALID_PORT_PARAMETER)
|
2019-09-23 17:39:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (new Address4(ip).isValid()) {
|
|
|
|
return multiaddr(`/ip4/${ip}/tcp/${port}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
const ip6 = new Address6(ip)
|
|
|
|
|
|
|
|
if (ip6.isValid()) {
|
|
|
|
return ip6.is4()
|
|
|
|
? multiaddr(`/ip4/${ip6.to4().correctForm()}/tcp/${port}`)
|
|
|
|
: multiaddr(`/ip6/${ip}/tcp/${port}`)
|
|
|
|
}
|
|
|
|
|
2020-02-13 16:22:12 +01:00
|
|
|
throw errCode(new Error(`invalid ip:port for creating a multiaddr: ${ip}:${port}`), errors.ERR_INVALID_IP)
|
2019-09-23 17:39:32 +02:00
|
|
|
}
|
2020-02-13 16:22:12 +01:00
|
|
|
|
2020-10-07 15:01:44 +02:00
|
|
|
module.exports = ipPortToMultiaddr
|
|
|
|
|
2020-02-13 16:22:12 +01:00
|
|
|
module.exports.Errors = errors
|