Get remote IP – cloudflare – apache reverse proxy – flask

Question:

I have setup apache reverse proxy for my flask app and everything is behind cloudflare.
I have restored original remote IP wiht this https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs
with Installing mod_remoteip

In apache access log there is restored IP so that is working, but in my flask app I can see only localhost 127.0.0.1.

I have also tried to check for:

print(request.headers.get('cf-connecting-ip'))
print(request.remote_addr)

but in both case there is only localhost IP.

 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 773-646-133
None
127.0.0.1
127.0.0.1 - - [08/Oct/2022 13:28:45] "GET / HTTP/1.1" 200 -

This is my apache config:

<VirtualHost *:80>
        ServerName xxx.xxx
        ServerAdmin [email protected]
        RemoteIPHeader CF-Connecting-IP

        ProxyPass / http://127.0.0.1:5000/
        ProxyPassReverse / http://127.0.0.1:5000/
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<IfModule mod_ssl.c>
        <VirtualHost *:443>
                ServerName xxx.xxx
                ServerAdmin [email protected]
                SSLCertificateFile /etc/cloudflare/xxx.pem
                SSLCertificateKeyFile /etc/cloudflare/xxx.key
                Protocols h2 h2c http/1.1
                RemoteIPHeader CF-Connecting-IP
                Include /etc/letsencrypt/options-ssl-apache.conf

                ProxyPass / http://127.0.0.1:5000/
                ProxyPassReverse / http://127.0.0.1:5000/
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined
        </VirtualHost>
</IfModule>

Is there any way, how I can get Remote IP in flask?

Thank you in advance.

Asked By: Da No

||

Answers:

The following method worked for us:

from flask import request

def ipaddress():
    try:
        if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
            ip_addr = request.environ['REMOTE_ADDR']
        else:
            ip_addr = request.environ['HTTP_X_FORWARDED_FOR']
        return ip_addr
    except Exception as err:
        print(f"Error getting ipaddress : {err}")