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

Tag: node.js Author: fangxxx1004 Date: 2010-06-17

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?

Best Answer

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.

comments:

and did you find another way?