Can I bind to a specific host? How is the host option passed through?
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
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
-
Default behavior (no host given):
getLocalHosts()builds the set of hosts to check by readingos.networkInterfaces()and adding every interface address, plusundefined(server default) and'0.0.0.0'(default IPv4 fallback) [index.js:L31-L45]. -
Actual availability check:
checkAvailablePort(options)creates anet.createServer()and callsserver.listen(options, ...)— theoptionsobject (which includeshostwhen provided) is passed straight through to Node'snet.Server#listen, and on success it resolves with the bound port before closing the server [index.js:L47-L59]. So thehostfield set inOptionsis forwarded verbatim into Node's ownlisten()call, meaning any host value Node'snet.listenaccepts (IPv4/IPv6 address) is valid here. -
Type signature:
OptionsextendsOmit<ListenOptions, 'port'>[index.d.ts:L3-L40], which is whyhost(and other Nodenet.ListenOptionsfields) can be passed alongsideport,exclude, andreserve.
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
reserveandhost: reserved ports are locked globally by port number, even if originally looked up with a specifichostoripv6Only[readme.md:L74-L78] [test.js:L207-L214], and there are tests confirming that even whenhostis omitted,ipv6Onlycombined with reservation still affects checks across IPv4/IPv6 [test.js:L219-L233].
FOLLOW_UPS:
- What does the
ipv6Onlyoption do exactly? - How does the
reserveoption lock ports internally? - How does
portNumbers()generate a port range?
Want to ask your own question?
Open chat for sindresorhus/get-portPublic 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.