diff --git a/lib/get-free-port.js b/lib/get-free-port.js index 7d73e4a..ebc26ef 100644 --- a/lib/get-free-port.js +++ b/lib/get-free-port.js @@ -3,21 +3,15 @@ const { Server } = require('net'); // This works by trying to listen on a port. // If connecting works then the port is good to use. // If not the port is busy, try another -async function getFreePort(port) { +function getFreePort(port, host) { return new Promise((resolve, reject) => { const server = new Server(); -// const timeout = () => { -// resolve(port); -// socket.destroy(); -// }; const next = () => { server.close(); resolve(getFreePort(++port)); }; -// setTimeout(timeout, 1000); -// server.on("timeout", timeout); server.on("listening", () => { server.close(); resolve(port); @@ -26,7 +20,7 @@ async function getFreePort(port) { server.listen({ port, - host: "0.0.0.0", + host, exclusive: true, }); }); diff --git a/lib/servez.js b/lib/servez.js index a4b96ff..518218d 100644 --- a/lib/servez.js +++ b/lib/servez.js @@ -236,11 +236,15 @@ class Servez extends EventEmitter { res.status(404).send(`
ERROR 404: No such path ${req.path}
`); } + async function getFreePortForLocalAndPublic(port) { + return await getFreePort(await getFreePort(port, '0.0.0.0'), '127.0.0.1'); + } + app.use(nonErrorLocalErrorHandler); app.use(localErrorHandler); (async () => { - const port = await getFreePort(settings.port); + const port = await getFreePortForLocalAndPublic(settings.port); if (!settings.scan && port !== settings.port) { const msg = `ERROR: port $${port} in use`; errorFiltered(Servez.MsgType.Error, msg); diff --git a/test/tests/servez-test.js b/test/tests/servez-test.js index 80a1237..beb0675 100644 --- a/test/tests/servez-test.js +++ b/test/tests/servez-test.js @@ -75,6 +75,14 @@ describe('servez-lib', () => { server2.servez.close(); }); + it('scans for port if only 127.0.0.1 is in use', async() => { + const server1 = await makeServer({local: true}); + const server2 = await makeServer(); + assert.notStrictEqual(server1.baseUrl, server2.baseUrl); + server1.servez.close(); + server2.servez.close(); + }); + it('does not scan for port when scan false', async() => { const server1 = await makeServer(); let threw = false;