3

I have a Google Cloud Function that is triggered by a HTML request. I need to get the source IP address. I've tried printing the whole request argument and it's not there.

Any ideas?

Note: this is NOT a duplicate of How to get client IP address in a Firebase cloud function?. The solution for Firebase Cloud Functions does not work on Google Cloud Functions.

Olav Gausaker
  • 496
  • 3
  • 14
  • 4
    You can retrieve the the source IP address using the [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) header. So in a [Google Cloud Function](https://cloud.google.com/functions/docs/writing/http#sample_usage) you can use the request object to get this header. For instance, you can use the **urllib** to get the [`request.get_header()`](https://docs.python.org/3/library/urllib.request.html) in Python – sllopis Jun 10 '20 at 09:41
  • I also found that you can also get the header in Flask using `request.headers.get("your-header-name")` or simply `request.headers["your-header-name"]` as a dictionary, or even `request.headers` to get all of them , according to this [Stackoverflow question](https://stackoverflow.com/questions/29386995/how-to-get-http-headers-in-flask) – sllopis Jun 10 '20 at 09:51
  • Cloud Functions work the same way regardless of how it was deployed. It's the same infrastructure for both gcloud and Firebase deployments. The only way things change is if you have Firebase Hosting in front of the function. Is that the case? Please edit the question to show a dump of the headers you're receiving that illustrate that things aren't working the way you expect. – Doug Stevenson Jun 10 '20 at 16:32
  • @Olav did you end up solving this? – ranni rabadi Nov 21 '20 at 11:47

1 Answers1

2

Just use request.headers['x-forwarded-for']. Make sure you're not using any middleware in ExpressJS, because of this

So instead of doing this:

const app = express()
const cors = require('cors')({ origin: true })
app.use(cors)

app.use(require('body-parser').json())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

just use this:

const app = express()
rantoniuk
  • 1,083
  • 12
  • 18