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 7/20/2026
Yes, you can bind to a specific host using the host option.
API definition: The host option is typed as readonly host?: string; in [index.d.ts:L38-L43], described as: "The host on which port resolution should be performed. Can be either an IPv4 or IPv6 address. By default, it checks availability on all local addresses defined in OS network interfaces. If this option is set, it will only check the given host." This matches the README description [readme.md:L83-L88].
How it flows through the code: In getAvailablePort, if options.host is truthy (or options.port === 0), the function skips iterating over all local interfaces and instead calls checkAvailablePort(options) directly — meaning only that specific host is checked:
const getAvailablePort = async (options, hosts) => {
if (options.host || options.port === 0) {
return checkAvailablePort(options);
}
for (const host of hosts) {
try {
await checkAvailablePort({port: options.port, host});
} catch (error) {
if (!['EADDRNOTAVAIL', 'EINVAL'].includes(error.code)) {
throw error;
}
}
}
return options.port;
};
[index.js:L61-L78]
If no host is specified, getLocalHosts() builds a set of all local addresses from os.networkInterfaces(), plus undefined (server default) and '0.0.0.0' (default IPv4 fallback), and getAvailablePort loops through each of them to check availability:
const getLocalHosts = () => {
const interfaces = os.networkInterfaces();
const results = new Set([undefined, '0.0.0.0']);
for (const _interface of Object.values(interfaces)) {
for (const config of _interface) {
results.add(config.address);
}
}
return results;
};
[index.js:L31-L46]
Tests confirming this behavior:
port can be bound to IPv4 host when promise resolves— binds0.0.0.0and verifiesserver.address().portmatches [test.js:L44-L52].preferred port given IPv4 host— requests port8081withhost: '0.0.0.0'and gets it back [test.js:L54-L62].preferred ports is bound up with different hosts— shows that ports bound on different hosts (default,0.0.0.0,127.0.0.1) are each treated as unavailable independently, andget-portcorrectly skips them when checking across hosts [test.js:L167-L176].
Also worth noting: there's an interaction with the reserve option — reserved ports are locked globally by port number regardless of which host was used to look them up, per [readme.md:L67-L71] and demonstrated in the test reserve option blocks the same port on other hosts too [test.js:L192-L198].
FOLLOW_UPS:
- What does the
ipv6Onlyoption do exactly? - How does
clearLockedPorts()work internally? - What happens when
port: 0is passed?
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.