Python: Check if an IP matches or in a valid range

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('')) or (ip in netaddr.IPNetwork('')) or (ip in netaddr.IPNetwork(''))

The example searches through 2 IP ranges and then compares to an exact IP match.


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog