NodeJS获取remoteAddress使用的IP [英] NodeJS get IP used by remoteAddress

查看:3514
本文介绍了NodeJS获取remoteAddress使用的IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个简单的NodeJS服务器使用NET,HTTP和UDP。每个服务器侦听端口X但具有多个IP地址。我希望在客户端连接到服务器时检索服务器的实际IP地址(客户端连接的IP,客户端必须写入的IP以连接到服务器)。

I have 3 simple NodeJS servers usign NET, HTTP and UDP. Each server listens on port X but has multiple IP addresses. I would like to retrive the actual IP address of the server when the client connects to the server (the IP to where the client connected, the IP that client had to write to connect to the server).

var httpService = http.createServer(function(req, res){
   req.getActualServerAddress();
});
httpService.listen(8000);

var netService = net.createServer(function(socket) {
   socket.getActualServerAddress();
});
netService.listen(8001);

var udpService = dgram.createSocket("udp4");
udpService.on("message", function (msg, rinfo){
   rinfo.getActualServerAddress();
});
udpService.bind(8002);

Thx。

推荐答案

如果未指定主机名,则服务器将从0.0.0.0开始。因此,您可能无法获得理想的结果[阅读Maqurading]。对于HTTP,您可以使用HTTP主机标头[自HTTP / 1.1以来必需],这可能对您的情况有益。

If you do not specify the hostname, the server will start at 0.0.0.0. So you may not get your desired outcome[ read Maqurading]. For HTTP you can use the HTTP "Host" header [mandatory since HTTP/1.1] which might be fruitful for your case.

您仍然可以试试:

socket.address()




返回由报告的套接字的绑定地址和端口
操作系统。返回具有两个属性的对象,例如
{address:192.168.57.1​​,port:62053}

Returns the bound address and port of the socket as reported by the operating system. Returns an object with two properties, e.g. {"address":"192.168.57.1", "port":62053}

以下是tcp的示例:

var netService = require('net').createServer(function(socket) {
 address = netService.address();
 console.log("Stream on %j", socket.address());
 console.log("opened server on %j", address);
});
netService.listen(8001);

http的样本:

var httpService = require('http').createServer(function(req, res){
console.log("Stream on %j", req.connection.address());
    res.end("Hi");
});
httpService.listen(8000);

这篇关于NodeJS获取remoteAddress使用的IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆