How to Get the Actual IP Address of Visitors in Python Flask

How to Get the Actual IP Address of Visitors in Python Flask: A Guide for Nginx and Cloudflare Users

Have you ever tried to get the actual IP address of a visitor? You might have created a web app using Python Flask. Maybe even with an authentication system so that your visitors can also create accounts. But oops! People are spamming it. So, you see the necessity of getting IP addresses to restrict users from creating multiple accounts. Or maybe you simply want to get the IP address for security purposes.

But How? Is there any way to get the real IP address of the user? In this article, we will show you how and clear all of your questions.

It can be tricky most of the time to get the real IP address of the visitors as they can use proxies. And in some cases, maybe the site itself is behind a proxy. As a result, you may grab the wrong IP instead. But don’t worry there are ways to make sure you don’t get the wrong IP.

By default, Flask provides the “request.remote_addr” property to get the IP address of the client, but this may not always give you the actual IP address of the visitor if you’re using a proxy server like Nginx or Cloudflare.

In this tutorial, we’ll show you how to get the actual IP address of visitors using Python Flask, and how to configure Nginx and Cloudflare to forward the correct IP address to your Flask application.

Prerequisite – Getting Started

Before we start, Open your terminal or command prompt and make sure have these installed on your system:

  • Python Installed on your system
  • Make sure you have the latest version of pip, which is the package installer for Python, by running the following command:
pip install --upgrade pip
  • Make sure you have Flask installed. You can Install Flask by running the following command:
pip install Flask

This will download and install Flask and its dependencies.

  • Verify that Flask is installed correctly by running the following Python code in your terminal:
python -c "import flask; print(flask.version)"


This should output the version number of Flask that you just installed.

You should also have a basic understanding of Python and Flask.

Getting the actual IP address of visitors in Flask

Getting The Actual IP address of visitors In Flask

To get the actual IP address of visitors in Flask, we need to look at the HTTP headers sent by the client. The “X-Forwarded-For” header and the “X-Real-IP” header are two common headers used by proxy servers to pass along the actual IP address of the client.

Here’s the code to get the actual IP address of visitors in Flask:

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    ip_address = request.headers.get('X-Forwarded-For', request.headers.get('X-Real-IP', request.remote_addr))
    return f'Your IP address is {ip_address}'

This code uses the “request.headers.get()” method to get the “X-Forwarded-For” header first, then falls back to the “X-Real-IP” header, and finally falls back to the “request.remote_addr” property if neither header is present. This ensures that we always get the actual IP address of the visitor if it is available.

Configuring Nginx to forward the correct IP address to Flask

Configuring Nginx to forward the correct IP address to Flask

If you’re using Nginx as a proxy server, you need to configure it to forward the actual IP address of the visitor to your Flask application. Here’s how you can do it:

  1. Add the following line to your Nginx configuration file:
proxy_set_header X-Real-IP $remote_addr;

This will set the X-Real-IP header to the actual IP address of the visitor.

  1. Add the following line to your Flask application to get the actual IP address from the “X-Real-IP” header:
ip_address = request.headers.get('X-Real-IP', request.remote_addr)

This will get the IP address from the “X-Real-IP” header if it is present, otherwise it will fall back to using the “request.remote_addr” property.

Here’s an example Nginx configuration file with the above line added:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

In the example above, Nginx is configured to proxy requests to “http://localhost:8000“. The “proxy_set_header” directive sets the Host and “X-Real-IP” headers to the values of the “$host” And “$remote_addr” variables respectively.

Configuring Cloudflare to forward the correct IP address to Flask

Configuring Cloudflare to forward the correct IP address to Flask

If you’re using Cloudflare as a proxy server, you also need to configure it to forward the actual IP address of the visitor to your Flask application. Here’s how you can do it:

Add the following line to your Flask application to get the actual IP address from the “CF-Connecting-IP” header:

ip_address = request.headers.get('CF-Connecting-IP', request.remote_addr)

This will get the IP address from the “CF-Connecting-IP” header if it is present, otherwise it will fall back to using the “request.remote_addr” property.

  1. Login to your Cloudflare account and select your website.
  2. Go to the “Network” tab and select the “HTTP” sub-tab.
  3. Scroll down to the “IP Address Headers” section and select “CF-Connecting-IP“.
  4. Click the “Save” button to apply the changes.

This will configure Cloudflare to forward the actual IP address of the visitor to your Flask application using the “CF-Connecting-IP” header.

Conclusion

In this tutorial, we’ve shown you how to get the actual IP address of visitors in Python Flask, including the process for dealing with proxy servers like Nginx and Cloudflare. By following the steps outlined in this post, you can ensure that your Flask application accurately records the IP address of visitors, which is crucial for various purposes like website analytics, security, and customization.

However, it’s essential to keep in mind that tracking visitors’ IP addresses raises privacy concerns and may be subject to various laws and regulations. Therefore, you should consider implementing appropriate security measures like SSL/TLS encryption, rate limiting, and logging policies to ensure that you handle visitor data responsibly.

Additionally, if your Flask application is hosted on a cloud platform or shared hosting service, there may be additional configurations required to handle IP address forwarding correctly. Be sure to consult the documentation of your hosting provider to ensure that you’re following the correct procedures.

In conclusion, accurately tracking visitors’ IP addresses can provide valuable insights into your web traffic and improve the overall user experience. With the steps outlined in this post, you’ll be able to get the actual IP address of visitors, even when using proxy servers like Nginx and Cloudflare, in your Flask application.

Was this helpful?

Mahedi Zaman Zaber

I'm a Driven and ambitious individual who is currently pursuing a Bachelor of Science in Computer Science and Engineering. With a passion for innovation and a desire to make a lasting impact, I aspire to become a distinguished software engineer and entrepreneur.

More Reading

Post navigation

ZealTyro Blog We would like to show you notifications for the latest news and updates.
Dismiss
Allow Notifications