[英]Cloud Run Service not picking up client correct IP address
I have a service hosted on Google Cloud Run.我在 Google Cloud Run 上托管了一项服务。 The service uses socket.io whenever the service is up and running.
只要服务启动并运行,该服务就会使用 socket.io。
When a socket client connects to the service I have the following function that gets the ip address of the connected client from the socket as shown below and then I am hitting this GeoPlugin Link with the retrieved IP当套接字客户端连接到服务时,我有以下 function 从套接字获取已连接客户端的 ip 地址,如下所示,然后我用检索到的 IP 点击此GeoPlugin 链接
async getSocketIP(socket) {
let { headers, address } = socket.handshake;
let { origin } = headers;
let ip = headers['x-forwarded-for'];
let userAgent = headers['user-agent'];
try {
let locationPointUrl = `http://www.geoplugin.net/json.gp?ip=${ip}`;
let { data: location } = await axios.get(locationPointUrl);
} catch (e) {
console.log(`Error get client online IP on Socket IO`);
}
}
Unfortunately, irrespective of the User's Location the IP always resolves to US.不幸的是,无论用户的位置如何,IP 总是解析为美国。
I have a custom domain mapped to the cloud run service via Domain Mapping.我有一个自定义域通过域映射映射到云运行服务。
What could be the reason the IP of the Client is always US IP? Client 的 IP 始终是 US IP 的原因可能是什么?
Please note that this same service when hosted on Heroku gets the correct IP address of the connected client.请注意,当托管在 Heroku 上时,相同的服务会获得已连接客户端的正确 IP 地址。
So, I'm very certain that it has something to do with Cloud Run.所以,我非常肯定它与Cloud Run有关。
All my services on Cloud Run are on US-CENTRAL1我在 Cloud Run 上的所有服务都在 US-CENTRAL1 上
For anyone who may experience something like this in the future.对于将来可能会遇到类似情况的任何人。
We had Cloudflare sitting in front of Cloud Run.我们让 Cloudflare 坐在 Cloud Run 前面。
So, to get the correct Client's IP address all we had to do was retrieve it from cf-connecting-ip
header instead of x-forwarded-for
.因此,要获得正确的客户端 IP 地址,我们所要做的就是从
cf-connecting-ip
header 而不是x-forwarded-for
检索它。
So, the modified and working code now becomes:因此,修改后的工作代码现在变为:
async getSocketIP(socket) {
let { headers, address } = socket.handshake;
let { origin } = headers;
let ip = headers['cf-connecting-ip'] ?? headers['x-forwarded-for']; //Notice the difference
let userAgent = headers['user-agent'];
try {
let locationPointUrl = `http://www.geoplugin.net/json.gp?ip=${ip}`;
let { data: location } = await axios.get(locationPointUrl);
} catch (e) {
console.log(`Error get client online IP on Socket IO`);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.