Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js:: what does hostname do in `listen` function?

Tags:

node.js

I own two domains, abc.com and xyz.com (not the real ones I own, but they work as an example). They both point to the same ip address. The following is my server js file:

var sys=require('sys'),
  http=require('http'),
  settings=require('./settings');



var srv = http.createServer(function(req, res) {
    var body="<b>Hello World!</b>"
    res.writeHead(200, {
        'content-length': body.length,
          'content-type': 'text/html',
          'stream': 'keep-alive',
          'accept': '*/*'
          }
      );
    res.end(body);
  });

srv.listen(8000, 'abc.com' ); // (settings.port, settings.hostname);

I then visit http://abc.com:8000/ and http://xyz.com:8000/ and they both display the webpage. I thought that I would only be able to see the page on abc.com since that's what I set as the hostname.

However, when I put '127.0.0.1' as the hostname, then I can only view the page via wget on the server itself.

So what does the hostname parameter do?

like image 879
Alexander Bird Avatar asked Jul 03 '10 22:07

Alexander Bird


People also ask

What does the listen () function do in node JS?

listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node's http.

What is the hostname of a node?

A hostname is a unique name for a computer or network node in a network. Hostnames are specific names or character strings that refer to a host and make it usable for the network and people.

What is App listen in node JS?

The app. listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc.

What do you think server listens exactly do why do we need it?

listen() is an inbuilt application programming interface of class Server within the http module which is used to start the server from accepting new connections.


1 Answers

The following segment of code inside net.js that defines the listen function is pertinent:

// the first argument is the port, the second an IP    
var port = arguments[0];
dns.lookup(arguments[1], function (err, ip, addressType) {
  if (err) {
    self.emit('error', err);
  } else {
    self.type = addressType == 4 ? 'tcp4' : 'tcp6';
    self.fd = socket(self.type);
    bind(self.fd, port, ip);
    self._doListen();
  }
});

So basically providing a url as the hostname parameter does not allow shared hosting. All node.js does is do the work for you of resolving a hostname to an ip address -- and since in my case both domains point to the same ip, both will work.

For me to do shared hosting, I must find another way.

like image 77
Alexander Bird Avatar answered Sep 24 '22 04:09

Alexander Bird