How to use the optional hostname parameter in Node.js server.listen()

倖福魔咒の 提交于 2019-12-04 07:11:44

So, you need a resolvable DNS host name for this to work. For a quick example, I edited the /etc/hosts file to include the following entry:

...
127.0.0.1 MyTestDnsHostName.local

then I flushed the resolver cache with the good old dscacheutil -flushcache and used the following bit of code in a simple Node.js server.

var http = require('http')
  , PORT = 8080;

function handleRequest( request, response ){
    response.end( 'It Works!' );
}

var server = http.createServer( handleRequest );

server.listen( PORT, "MyTestDnsHostName.local", 34, function(){
    console.log( "Server listening on port:%s", PORT );
});

And sure enough it works.

The error EADDRNOTAVAIL means that it's resolvable but not available; now, to be able to bind to it, it should be bindable (available) as well.

You can do a lsof -i TCP to check where it's binded.

However, I don't see why you have to bind the server elsewhere; binding to the loopback is the best practice.


Yeah, so it's actually a security flaw; if you bind it to all available interfaces 0.0.0.0, what you're essentially saying is that Listen to every available network interface there is. This may pose a security vulnerebility as it may bind to adapters you don't want it on; I've had first-hand experience of this while deploying a RoR application.

The 0.0.0.0/0 subnet is a very fancy way of saying: these are all the network interfaces I have on this computer, whilst 127.0.0.1 is ALWAYS the local-only interface. If you bind it to this, you get rid of quite a few security problems. One of which can be that the "hacker" tries to attach a listener on all interfaces, and if you don't have a very strict firewall, somewhere or the other, a leak may be present.

This is not a rule as such, but just a best practice.

P.S.: The code is a snippet I pulled off from Modulus' blog; it's quick if I want to try something out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!