Burg
Burg

Reputation: 189

Node.JS .listen(port, 'hostname') does not work

I am trying to spin up a node.js server and I want to understand the arguments of server.listen:

server.listen(port, hostname, backlog, callback);

As far as I understand this, the 2nd argument of listen should be a hostname. The result should be, that I am able to reach the server over "hostname:7000" but the result is that the script is crashing. Without "hostname" everything works fine. Whats the problem here? What is the usage of "hostname"?

const server = http.createServer(function (req, res) {    
console.log(req); 

}); 

server.listen(7000, "bla");

Browser:

bla:7000

doesn't work.

Error:

Error: listen EADDRNOTAVAIL 22.0.0.0:7000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1246:19)
at listen (net.js:1295:10)
at net.js:1405:9
at _combinedTickCallback (internal/process/next_tick.js:77:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
at Module.runMain (module.js:606:11)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)

Upvotes: 2

Views: 5429

Answers (3)

Didier68
Didier68

Reputation: 1323

I had a similar problem, because the router or the proxy modified the hostname of the request... The result was 2 differents names for intranet and extranet clients.

My solution was to set blank the hostname

server.listen(7000, "")

Upvotes: 0

Akhil Bojedla
Akhil Bojedla

Reputation: 2228

You are not allowed to give any random string as host argument. The server tries to bind itself to the provided hostname. So your hostname should either be your ip or a reachable hostname from the dns.

If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.

Upvotes: 1

robertklep
robertklep

Reputation: 203359

The hostname argument is used in situations where a server has more than one network interface, and you only want the server to listen on one of those interfaces (as opposed to the default, which is to listen to all interfaces).

For instance, if you want the server to be only accessible by clients running on the server itself, you make it listen on the loopback network interface, which has IP-address "127.0.0.1" or hostname "localhost":

server.listen(7000, "localhost")
server.listen(7000, "127.0.0.1")

It doesn't mean that you can just enter any hostname and magically get the ability to access the server through that hostname, that's not how it works or what it is intended for.

Upvotes: 5

Related Questions