* Splits a hostport string, e.g. "www.example.com:80", into its component * parts. * * @param {string} hostport The string to split. * @return {{host: string, port: ?number}} A host and port. If no port is * present in the argument `hostport`, port is null.
(hostport)
| 85 | * present in the argument `hostport`, port is null. |
| 86 | */ |
| 87 | function splitHostAndPort(hostport) { |
| 88 | let lastIndex = hostport.lastIndexOf(':') |
| 89 | if (lastIndex < 0) { |
| 90 | return { host: hostport, port: null } |
| 91 | } |
| 92 | |
| 93 | let firstIndex = hostport.indexOf(':') |
| 94 | if (firstIndex != lastIndex && !hostport.includes('[')) { |
| 95 | // Multiple colons but no brackets, so assume the string is an IPv6 address |
| 96 | // with no port (e.g. "1234:5678:9:0:1234:5678:9:0"). |
| 97 | return { host: hostport, port: null } |
| 98 | } |
| 99 | |
| 100 | let host = hostport.slice(0, lastIndex) |
| 101 | if (host.startsWith('[') && host.endsWith(']')) { |
| 102 | host = host.slice(1, -1) |
| 103 | } |
| 104 | |
| 105 | let port = parseInt(hostport.slice(lastIndex + 1), 10) |
| 106 | return { host, port } |
| 107 | } |
| 108 | |
| 109 | // PUBLIC API |
| 110 | module.exports = { |