Why doesn't this IP address work for Node.js c

2020-04-21 00:56发布

I have an unusual problem. I am running a simple node.js app. The code below works.

var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);

app.listen(8000, '127.0.0.1');

However, if I use app.listen(8000, '192.168.1.4');, no client is able to connect to the server. 192.168.1.4 is the IP address of my local machine.

One thing I noticed is that even when app.listen(8000, '127.0.0.1'); is used, on the local browser, http://localhost:8000/ works but http://192.168.1.4:8000/ does not work.

Can anyone what have I done wrong?

2条回答
Melony?
2楼-- · 2020-04-21 01:31

The line:

app.listen(8000, IP_ADDRESS);

means to listen to port 8000 on the device (ethernet, wifi, loopback) that owns that IP address for connections destined to that IP address.

Therefore, if you use 127.0.0.1 only localhost can connect to it and if you use 192.168.1.4 localhost cannot connect to it and only machines on the 192.168.1.xxx network can connect to it (I'm assuming a netmask of /8).

In order to allow both networks to connect, you can listen to both IP addresses:

var http = require('http');

var app1 = http.createServer(handler);
app1.listen(8000, '127.0.0.1');

var app2 = http.createServer(handler);
app2.listen(8000, '192.168.1.4');

Or, if you don't care about where the request comes from and want it to listen to packets coming from anywhere, simply don't pass it an IP address:

// listen to port 8000 on all interfaces:
app.listen(8000);
查看更多
萌系小妹纸
3楼-- · 2020-04-21 01:46

127.0.0.1 (localhost) is the IP address for the loopback adapter. The loopback adapter is a special interface that essentially allows programs to talk to each other on the same machine (communication bypasses physical interfaces).

Your actual IP address (the one that doesn't work in your example) is bound to a network device such as an ethernet adapter.

As suggested, using 0.0.0.0 (all available interfaces) should work if you want to expose your API externally.

查看更多
登录 后发表回答