如何使用节点 grpc 获取客户端 IP 地址



早些时候,我使用以下代码来获取客户端 IPexpress.js

req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress

想知道使用grpc节点应用程序获取客户端IP的方法是什么。 我尝试了getPeer((,即使API调用来自外部,它也始终提供ipv4:127.0.0.1:33944。

等效于下面的 go 代码是否有效?

call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString();

您可以通过以下方式获取客户端 IP 和端口:

const SayHello = async function (call, callback) {
const IPandPort = call.getPeer(); // like 127.0.0.1:8080 or just get 127.0.0.1
console.log(IPandPort);
}

请参阅以下问题以获取更多信息:

  • https://github.com/grpc/grpc-node/pull/1526

  • https://github.com/grpc/grpc-node/issues/1483

最新更新