Bits About Localhosts

I was playing a bit today with my local host. Basically I wanted to make it available over the net. This task is somewhat complicated or not depending on your network. For example, a few months ago, when I was using a different ISP and a different router, if I wanted to expose my local server to the whole world over the net I just had to rout http requests to my computer’s internal IP, that is usually something like 192.168.1.1 It was all good, but now I’m having trouble doing the same. I’ve set the router’s settings so that it should be sending all http connections to my computer to handle them, but it just doesn’t do it. At most I can access my local server from within my network. That is, my devices currently connected to the router.

To do this, I need only enter the ip address of my computer in the address bar of the browser. For example, in my tablet I enter 192.168.1.67, which is my laptop’s assigned ip address. This works well, and I am able to see the index page of my apache server’s home directory. So, I wanted to do the same with node, because I was also playing with node.

I created a small and useless server with node, and set it to listen on port 1337. Then, on the tablet I enter the address 192.168.1.67:1337, and nothing happens. The tablet cannot establish a connection with node. But on the computer, if I enter localhost:1337, everything works great. So I ask myself what could be the problem here.

I take another look at my node.js server, and find this line:

server.listen(1337, “127.0.0.1”);

And that makes me think. It is obvious that the server is listening to 127.0.0.1, but so is apache, and there is no problem with apache. Then it occurs to me that everything might work if I set node.js to listen to the ip assigned to the computer by the router rather than to 127.0.0.1, so I change that line to

server.listen(1337, “192.168.1.67”);

refresh the browser on the tablet, and it works. So what is the problem here?
Clearly, the problem is that the server is bound to the wrong ip address. So, how come apache works with no problem? Well, that is because apache listens to all addresses in the machine by default. So when I access 192.168.1.67, apache is listening to that address and that is why it serves the page without any problem. If we want to achieve the same result in node.js, we need to leave that second parameter empty for the listen method:

server.listen(1337);

This solves the problem, now I can access the node.js server from the tablet using my computer’s ip address and from the computer itself using localhost, because seriously, it is far more comfortable than writing an ip address.

The problem with exposing the server to the outside world is still there, but for now I’m OK with what I learned.