Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Available port for any localhost host (localhost, 0.0.0.0, 127.0.0.1) #48

Closed
dylang opened this issue May 29, 2020 · 1 comment · Fixed by #56
Closed

Comments

@dylang
Copy link

dylang commented May 29, 2020

If server.listen is used with a host, then get-port only returns the correct result if the same host value is provided.

// Some other project running on your machine:
server.listen(3000, 'localhost', cb);

This works, because we put in the host localhost, matching above:

// Your project:
await getPort({ port: 3000, host: 'localhost' }) 
// => Random port that is not bound to localhost, good!

However, when you don't know what host was used in the other project, or what host will be used in yours, you could be in trouble:

// Some other project running on your machine:
server.listen(3000, 'localhost', cb);

// Your project does one of these:

await getPort({ port: 3000 }) 
// => 3000...

await getPort({ port: 3000, host: '0.0.0.0' }) 
// => 3000...

await getPort({ port: 3000, host: '127.0.0.1' }) 
// => 3000...

await getPort({ port: 3000, host: '::' }) 
// => 3000...

If that 3000 port is then used later in your code with localhost, it will fail.

This might be a deficiency or feature in libev, or I'm not understanding how port binding works when the host is provided.

Workaround 1

Always use the same host when creating your server as used when running get-port. I'm finding that to not always be feasible.

Workaround 2

Math.max(
  await getPort({ port: 3000, host: 'localhost' }),
  await getPort({ port: 3000, host: '0.0.0.0' })
);
// => Will always be a random port, even if 3000 is available, 
// because `lockedPorts` ignores the `host`, so one of the two 
// getPort calls will think 3000 is already locked and return a random port.

Potential solution?

Maybe a possible workaround is to allow for passing in an array of hosts, or an option to check all localhost variants?

@dylang dylang changed the title Feature request: Available port for any localhost host valu (localhost, 0.0.0.0, 127.0.0.1) Feature request: Available port for any localhost host (localhost, 0.0.0.0, 127.0.0.1) May 29, 2020
@sindresorhus
Copy link
Owner

sindresorhus commented May 30, 2020

See my comment in #31 (comment). I think it indeed should just work by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants