简体   繁体   English

为什么此 IP 地址不适用于 Node.js 客户端?

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

I have an unusual problem.我有一个不寻常的问题。 I am running a simple node.js app.我正在运行一个简单的 node.js 应用程序。 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');但是,如果我使用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. 192.168.1.4是我本地机器的IP地址。

One thing I noticed is that even when app.listen(8000, '127.0.0.1');我注意到的一件事是,即使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.使用,在本地浏览器上, http://localhost:8000/有效,但http://192.168.1.4:8000/无效。

Can anyone what have I done wrong?谁能告诉我我做错了什么?

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.意味着在拥有该 IP 地址的设备(以太网、wifi、环回)上侦听端口 8000,以便连接到该 IP 地址。

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 ).因此,如果您使用127.0.0.1 ,则只有 localhost 可以连接到它,如果您使用192.168.1.4 localhost 无法连接到它,并且只有192.168.1.xxx网络上的机器可以连接到它(我假设网络掩码为/8 )。

In order to allow both networks to connect, you can listen to both IP addresses:为了允许两个网络连接,您可以监听两个 IP 地址:

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:或者,如果您不关心请求来自何处并希望它侦听来自任何地方的数据包,只需不要将 IP 地址传递给它:

// listen to port 8000 on all interfaces:
app.listen(8000);

127.0.0.1 ( localhost ) is the IP address for the loopback adapter. 127.0.0.1 ( localhost ) 是环回适配器的 IP 地址。 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.您的实际 IP 地址(在您的示例中不起作用的地址)绑定到网络设备,例如以太网适配器。

As suggested, using 0.0.0.0 (all available interfaces) should work if you want to expose your API externally.正如所建议的,如果您想在外部公开 API,使用0.0.0.0 (所有可用接口)应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM