While implementing a certain feature, we wanted to restrict it's functionality to a range of IP's only available in the office.
To do that, you first need to download netaddr from github.
import netaddr
def cache_purge_allowed(request):
client_ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', None))
if client_ip is None:
return False
ip = netaddr.IPAddress(client_ip)
return (ip in netaddr.IPNetwork('203.34.46.0/23')) or (ip in netaddr.IPNetwork('192.168.0.0/16')) or (ip in netaddr.IPNetwork('119.225.10.1'))
The example searches through 2 IP ranges and then compares to an exact IP match.