[英]How to get client IP address in a Firebase cloud function?
When saving data to Firebase database with a Firebase cloud function, I'd like to also write the IP address where the request comes from. When saving data to Firebase database with a Firebase cloud function, I'd like to also write the IP address where the request comes from.
However, req.connection.remoteAddress
always returns ::ffff:0.0.0.0
.但是,
req.connection.remoteAddress
总是返回::ffff:0.0.0.0
。 Is there a way to get the actual IP address of the client that makes the request?有没有办法获取发出请求的客户端的实际 IP 地址?
EDIT: This seems to be outdated.编辑:这似乎已经过时了。 See the other answer.
见另一个答案。
The IP address seems to be available in req.headers["x-forwarded-for"]
. IP 地址似乎在
req.headers["x-forwarded-for"]
可用。 I didn't find official information on this in the documentation, though.不过,我没有在文档中找到这方面的官方信息。
Also please note that if the client itself sends eg X-Forwarded-For: 1.2.3.4
, the values are concatenated:另请注意,如果客户端本身发送例如
X-Forwarded-For: 1.2.3.4
,则这些值将被连接:
"x-forwarded-for":"1.2.3.4, actual-client-ip-as-seen-by-google"
如果您正在寻找通过 firebase 托管的客户端 ip,您应该使用标头fastly-client-ip
将有真正的客户端 ip。
The clients IP is in request.ip
.客户端 IP 在
request.ip
。
Example:示例:
export const pay = functions.https.onRequest((request, response) => {
console.log(`My IP is ${request.ip}`);
});
If you are looking for ip address or headers in cloud callable function, then you can get information inside context object.如果您正在云可调用函数中查找 ip 地址或标头,那么您可以在上下文对象中获取信息。
for ex:例如:
exports.testUser = async (data, context) => {
console.log('------------------------::context::------------------');
if(context.rawRequest && context.rawRequest.headers){
console.log(context.rawRequest.headers);
}
}
In the headers you can get ip : header { 'x-appengine-user-ip' : 'xxip' } etc.在标题中,您可以获得 ip : header { 'x-appengine-user-ip' : 'xxip' } 等。
This worked for me:这对我有用:
const express = require('express');
const logIP = async (req : any, res : any, next : any) => {
const clientIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.headers['fastly-client-ip'];
}
const logIPApp = express();
logIPApp.use(logIP);
exports.reportIP = functions.https.onRequest(logIPApp);
This is what worked for me using Firebase Cloud Functions:这就是使用 Firebase 云函数对我有用的方法:
const clientIP = req.headers['x-appengine-user-ip'] || req.header['x-forwarded-for']
Note, that this doesn't work locally!请注意,这在本地不起作用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.