Posted Nov. 21, 2019

How to show to visotor their IP address

As promised, here is how I recreated my /ip/ page in Django:

I created a new Django app (obviously); `ip`

in there is the minimal stuff to define the app:


from django.apps import AppConfig

class IpConfig(AppConfig):

name = "ip"

``` is almost empty:


from django.db import models


and in, the magic happens:


from django.shortcuts import render, HttpResponse

def get_client_ip(request):

x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")

if x_forwarded_for:

ip = x_forwarded_for.split(",")[0]


ip = request.META.get("REMOTE_ADDR")

resp = "{}".format(ip)

return HttpResponse(resp)


The "HTTP_X_FORWARDED .." part is something your browser supplies, so this could all be spoofed, so it might not be useful as a security measure, but still useful for non-nefferious purposes.