Nov 25, 2012

Node JS - Listen to External IP Address

Posted Nov 25, 2012
I wanted to try my local server in an iPad device and when I accessed its external port (192.168.0.24) in our intranet, it's not working. At first I changed the listen address from 127.0.0.1 to 192.168.0.24 and it worked, the problem was I cannot access http://localhost:3000 after. In addition, this approach of hardcoding the address is not an acceptable solution in the long run; there must be another way.

How to make your node js server listen to external ip

The fix is easy but not very intuitive. Just change the listen address from 127.0.0.1 to 0.0.0.0

I encountered a minor hiccup: I stored the address in a global variable and used it in a special function that accessed my own server. So my function was trying to access http://0.0.0.0:3000/... and it wouldn't work this way. So I just retained the 127.0.0.1 for my special functions.

I wonder why node js decided to implement it this way (or I'm not sure if it's Express js that's the culprit here). Why not just listen to all available IP Addresses when you specify 127.0.0.1? Maybe it's a security issue; I don't know.

[Update 18-Feb-2013] As "Reality Check" pointed out, NodeJS can listen to any IP address if you don't specify the host parameter. It's right here in NodeJs API:


server.listen(port, [hostname], [backlog], [callback])
Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

5 comments:

  1. I hit this same issue. The answer is if you specify an IP, it will be only on that IP. In *nix, 127.0.0.1 does not imply external IP. To do this properly, don't specify the IP address in the call to listen() and Node will listen on all IP addresses. The 0.0.0.0 solution is neat but it seems redundant.

    ReplyDelete
  2. Yes, you're right! Thanks for pointing it out, and it's in the API which I didn't take time to read: http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback

    ReplyDelete
  3. t43rfeferffef

    ReplyDelete
  4. ffdsdvdfvfvfvfvfvf

    ReplyDelete
  5. rgrgrggergverggggregrgrg

    ReplyDelete