2

According to the docs, creating a server can optionally listen to a specific host:

server.listen(port, [host], [backlog], [callback])

Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

So you can listen to a single host, or to any host.

Is there a way to listen to a few specific hosts?

2
  • 1
    Or you could just check req.headers.host and respond with a 404 for all but the ones you'd like to respond to. Commented Jan 17, 2014 at 14:33
  • @adeneo Your proposal assumes nothing else needs his port on the other interfaces. There are also some security issues with what you propose in some cases. Handling TCP connections and how you deal with requests at the application layer are completely separate issues. Commented Jan 17, 2014 at 14:52

1 Answer 1

7

To do this, you must add additional HTTP servers. However, you can use the same callback for each.

If you are using Express, this is as simple as an additional call to app.listen().

Sign up to request clarification or add additional context in comments.

5 Comments

Ah same callback, that's great. I can loop through an array of hosts and attach the callback to each.
Note: this requires using different ports for each host or you'll get an EADDRINUSE error
@caseyWebb That's not true. You can listen on the same port, on different hosts/addresses.
Could you provide an example? I just tried this (hosts.forEach((host) => app.listen(port, host))) and it threw the above error.
@caseyWebb Post a new question, and in it list out your hosts. Drop a link to it here and I'll take a look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.