My IP

Posted Nov. 21, 2019

How to show a visitor their IP address

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

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

in apps.py there is the minimal stuff to define the app:

```python

from django.apps import AppConfig

class IpConfig(AppConfig):

name = "ip"

```

models.py is almost empty:

```python

from django.db import models

```

and in views.py, the magic happens:

```python

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]

else:

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 practical purposes.