如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

以下函数涵盖了所有的情况,将会有所帮助

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}console.log("client IP is *********************" + ip);

其他回答

也有同样的问题…im也是新的javascript,但我解决了这个与req.connection.remoteAddress;这给了我IP地址(但在ipv6格式::ffff.192.168.0.101),然后.slice删除前7位数字。

var ip = req.connection.remoteAddress;

if (ip.length < 15) 
{   
   ip = ip;
}
else
{
   var nyIP = ip.slice(7);
   ip = nyIP;
}

获取ip地址有两种方式:

让IP = req.ip 让ip = req.connection.remoteAddress;

但上述方法存在一个问题。

如果你在Nginx或任何代理程序后面运行你的应用程序,每个IP地址将是127.0.0.1。

因此,获取user的ip地址的最佳方案是:-

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

函数getCallerIP(请求){ Var IP = request。标题(“x-forwarded-for”)| | request.connection.remoteAddress | | request.socket.remoteAddress | | request.connection.socket.remoteAddress; IP = IP .split(',')[0]; IP = IP .split(':').slice(-1);//如果IP以“::ffff:146.xxx.xxx.xxx”格式返回 返回的ip; }

请求。headers['x-forwarded-for'] || request.connection.remoteAddress . headers['x-forwarded-for'

如果有x-forward -for报头,则使用它,否则使用. remoteaddress属性。

The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.

警告:

不要盲目地将其用于重要的速率限制:

let ip = request.headers['x-forwarded-for'].split(',')[0];

这很容易被欺骗:

curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"

在这种情况下,用户的真实IP地址将是:

let ip = request.headers['x-forwarded-for'].split(',')[1];

我很惊讶,没有其他答案提到这一点。