Generate a random IP address in Python

01 June 2019   0 comments   Python, Django

I have a commenting system where people can type in a comment and optionally their name and email if they like.
In production, where things are real, the IP address that can be collected are all interestingly different. But when testing this manually on my laptop, since the server is running http://localhost:8000, the request.META.get('REMOTE_ADDR') always becomes . Boring! So I fake it. Like this:

import random
from ipaddress import IPv4Address

def _random_ip_address(seed):
    return str(IPv4Address(random.getrandbits(32)))

# Here's the code deep inside the POST handler just before storing 
# the form submission the database.

if settings.DEBUG and metadata.get("REMOTE_ADDR") == "":
    # Make up a random one!
    metadata["REMOTE_ADDR"] = _random_ip_address(
        str(form.cleaned_data["name"]) + str(form.cleaned_data["email"])

It's pretty rough but it works and makes me happy.


Your email will never ever be published

Related posts

How I simulate a CDN with Nginx 15 May 2019
Build an XML sitemap of XML sitemaps 01 June 2019