1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/main/port.ts
Alexis Deruelle 6412d73a5a
Fix port availability test (#333)
* Let OS allocate port number

Port availability might be tricky if some port is already in use on the
'all' interface '0.0.0.0'.

The proposed solution is to let the OS allocate the port for us using 0
as port specifier :

- first create a server instance to allocate a port number
- save port number
- close the server
- return the port number to the caller

This should be safe granted the OS doesn't reuse the port numbers on
consecutive port allocations.

see :
- about Node.js Net module : https://nodejs.org/docs/latest-v12.x/api/net.html#net_server_listen_port_host_backlog_callback
- about safety around reusing port number : https://unix.stackexchange.com/a/132524

Signed-off-by: Alexis Deruelle <alexis.deruelle@gmail.com>
2020-05-05 07:31:58 +03:00

31 lines
897 B
TypeScript

import logger from "./logger"
import { createServer } from "net"
import { AddressInfo } from "net"
const getNextAvailablePort = () => {
logger.debug("getNextAvailablePort() start")
const server = createServer()
server.unref()
return new Promise<number>((resolve, reject) =>
server
.on('error', (error: any) => reject(error))
.on('listening', () => {
logger.debug("*** server listening event ***")
const _port = (server.address() as AddressInfo).port
server.close(() => resolve(_port))
})
.listen({host: "127.0.0.1", port: 0}))
}
export const getFreePort = async () => {
logger.debug("getFreePort() start")
let freePort: number = null
try {
freePort = await getNextAvailablePort()
logger.debug("got port : " + freePort)
} catch(error) {
throw("getNextAvailablePort() threw: '" + error + "'")
}
return freePort
}