Javascript Node.js server.address().address 返回 ::

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33853695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:33:41  来源:igfitidea点击:

Node.js server.address().address returns ::

javascriptnode.jsexpressipv6

提问by Jake

If I remember correctly it used to display "localhost" a few days ago. I am not sure what had changed that made server.address().address return double colons (::) instead. I read here that it returns an IPv6 address (::) if it is available but it's disabled on my PC. https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback

如果我没记错的话,几天前它曾经显示“localhost”。我不确定是什么改变了 server.address().address 返回双冒号 (::)。我在这里读到它会返回一个 IPv6 地址 (::)(如果可用),但它在我的 PC 上被禁用。 https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback

回答by Alexander Mikhalchenko

As the docs say,

正如文档所说,

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A port value of zero will assign a random port.

开始接受指定端口和主机名上的连接。如果省略主机名,则当 IPv6 可用时,服务器将接受任何 IPv6 地址 (::) 上的连接,否则接受任何 IPv4 地址 (0.0.0.0) 上的连接。端口值为零将分配一个随机端口。

So, the following code would print running at http://:::3456:

因此,以下代码将打印running at http://:::3456

var express      = require('express');
var app          = express();
var server = app.listen(3456, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('running at http://' + host + ':' + port)
});

But if you add an explicit hostname:

但是如果你添加一个明确的主机名:

var server = app.listen(3456, "127.0.0.1", function () {

It would print what you want to see: running at http://127.0.0.1:3456

它会打印您想看到的内容: running at http://127.0.0.1:3456

Also you might want to use some IP libas pointed in this answer

此外,您可能想使用此答案中指出的一些 IP 库

Best regards, Alexander

最好的问候,亚历山大

回答by Nikhil

The reason why its choosing IPV6 address is possibly because some other process is using IPV4 port no 3456. This happens sometimes due to automatic updates where new processes are installed.

它选择 IPV6 地址的原因可能是因为某些其他进程正在使用 IPV4 端口号 3456。有时会发生这种情况是由于安装了新进程的自动更新。