Node.js 如何获取侦听特定端口的http 服务器的IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24378272/
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-09-02 17:31:46  来源:igfitidea点击:

Node.js How to get the IP address of http server listening on a specific port

node.js

提问by Sohaib

I've a following very basic code of HTTP server which is listening on port 8000. How to determine the IP address of server, can it be retrieved from the 'server' variable? I am working on an application where I need to automatically send the server Info (ip,port etc..) to redis store.

我有以下非常基本的 HTTP 服务器代码,它正在侦听端口 8000。如何确定服务器的 IP 地址,是否可以从“服务器”变量中检索?我正在开发一个应用程序,我需要自动将服务器信息(ip、端口等)发送到 redis 存储。

I'm new to node.js, Thanks for the help

我是 node.js 的新手,感谢您的帮助

var http = require("http");
var server = http.createServer(function(request, response) {
??response.writeHead(200, {"Content-Type": "text/html"});
??response.write("Hello!!!");
??response.end();
});

?

?

server.listen(8000);
console.log("Server is listening....");

回答by f1lt3r

Use the following:

使用以下内容:

server.address()

Which logs something like:

其日志类似于:

{ address: '0.0.0.0', family: 'IPv4', port: 8080 }

To log the IP of your server to the console, use:

要将服务器的 IP 记录到控制台,请使用:

console.log( server.address().address );

回答by Tom Grant

Assuming you want the address your server is bound to, you can use server.address.addressto get the IP address the server is bound to. Similarly, you can use server.address.portto get the port number that the server is bound to.

假设您想要您的服务器绑定到的地址,您可以使用server.address.address来获取服务器绑定到的 IP 地址。同样,您可以使用server.address.port获取服务器绑定到的端口号。

From: http://nodejs.org/api/net.html#net_server_address.

来自:http: //nodejs.org/api/net.html#net_server_address

回答by mostafa.mortazavi

req.connection.remoteAddress
req.connection.remotePort
req.connection.localAddress
req.connection.localPort