简体   繁体   中英

Cloud Run Service not picking up client correct IP address

I have a service hosted on Google Cloud Run. The service uses socket.io whenever the service is up and running.

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

    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.

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?

Please note that this same service when hosted on Heroku gets the correct IP address of the connected client.

So, I'm very certain that it has something to do with Cloud Run.

All my services on Cloud Run are on US-CENTRAL1

For anyone who may experience something like this in the future.

We had Cloudflare sitting in front of 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 .

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`);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM