RepoPilot

Can I bind to a specific host? How is the host option passed through?

About sindresorhus/get-port · 2 messages · last activity 8/1/2026

Question

Can I bind to a specific host? How is the host option passed through?

RepoPilot

Yes — get-port supports a host option for scoping port lookups to a specific address.

How it's documented

The host option is string typed: an IPv4 or IPv6 address. By default (when omitted), get-port checks availability across all local addresses from the OS network interfaces; if you set host, it restricts the check to just that address [readme.md:L84-L91] [index.d.ts:L36-L41].

How it flows through the code

  1. Default behavior (no host given): getLocalHosts() builds the set of hosts to check by reading os.networkInterfaces() and adding every interface address, plus undefined (server default) and '0.0.0.0' (default IPv4 fallback) [index.js:L31-L45].

  2. Actual availability check: checkAvailablePort(options) creates a net.createServer() and calls server.listen(options, ...) — the options object (which includes host when provided) is passed straight through to Node's net.Server#listen, and on success it resolves with the bound port before closing the server [index.js:L47-L59]. So the host field set in Options is forwarded verbatim into Node's own listen() call, meaning any host value Node's net.listen accepts (IPv4/IPv6 address) is valid here.

  3. Type signature: Options extends Omit<ListenOptions, 'port'> [index.d.ts:L3-L40], which is why host (and other Node net.ListenOptions fields) can be passed alongside port, exclude, and reserve.

Behavior confirmed by tests

  • Passing host: '0.0.0.0' after a port is bound to that host correctly returns a different, available port [test.js:L43-L52], and preferred ports are checked against that specific host [test.js:L54-L70].
  • When multiple hosts have bound the same preferred port (e.g., default, '0.0.0.0', '127.0.0.1'), get-port correctly skips those and returns the next free one — showing host-scoped checking in action [test.js:L167-L177].
  • There's a subtlety around reserve and host: reserved ports are locked globally by port number, even if originally looked up with a specific host or ipv6Only [readme.md:L74-L78] [test.js:L207-L214], and there are tests confirming that even when host is omitted, ipv6Only combined with reservation still affects checks across IPv4/IPv6 [test.js:L219-L233].

FOLLOW_UPS:

  • What does the ipv6Only option do exactly?
  • How does the reserve option lock ports internally?
  • How does portNumbers() generate a port range?

Want to ask your own question?

Open chat for sindresorhus/get-port

Public Q&A. Generated by RepoPilot from the actual source of sindresorhus/get-port. AI answers can be incomplete or stale — verify before relying on them.