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

亡梦爱人 提交于 2020-05-09 07:00:07

问题


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?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/31738968/why-doesnt-this-ip-address-work-for-node-js-clients

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