'Which ip address triggered my HTTP Cloud Function?
I would like to see which IP address triggered my HTTP triggered Cloud Function.
This is the (demo code) of my python cloud function:
def hello_world(request):
request_json = request.get_json()
if request.args and 'message' in request.args:
return request.args.get('message')
elif request_json and 'message' in request_json:
return request_json['message']
else:
return f'Hello World!'
Solution 1:[1]
Since Python Cloud Functions on GCP are using Flask you can add the following to your code:
# get ip address for logging purposes
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
print(f"IP address: {request.environ['REMOTE_ADDR']}")
else:
print(f"IP address: {request.environ['HTTP_X_FORWARDED_FOR']}") # if behind a proxy
See also: Get IP address of visitors using Flask for Python
Print statements get sent to Cloud Logging, so the ip address will be visible in the logging.
To find your ip address log entry faster you can filter in Cloud Logging with:resource.labels.function_name="name_of_your_cloud_function"
Above answer is for 1st generation Cloud Functions.
When using 2nd generation Cloud Functions you don't need to add specific code to check the ip address of the function caller.
You can just check Cloud Logging and filter on:resource.type="cloud_run_revision"
Solution 2:[2]
Arrays decay to pointers.
char cha[] = "abcde";
char *p1 = cha;
char (*arrayptr)[sizeof(cha)] = &cha;
cha, &cha[0] and &cha reference the same first element of the array cha, the only difference is the type.
chaand&cha[0]has type: pointer tochar&chahas type: pointer to array of 6charelements.
Solution 3:[3]
If your compiler supports typeof extension (gcc does) then you can define the pointer as:
typeof(char (*)[6]) arrayAddress = &cha;
Or even cleaner as:
typeof(char[6]) * arrayAddress = &cha;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Chris |
| Solution 3 |
