INTERNAL_IPS = [
'192.168.0.0/24', # site1 users
'10.0.0.0/8', # site2 users
'192.168.99.0/24', # VPN users
'127.0.0.1', # localhost
]
I've cobbled together a Netblock class and a Netblocks container
class (along with some utility functions) which allow for easy
testing of the membership of an IP address, so the above would
become (using multiple notations for example's sake)
INTERNAL_IPS = Netblocks([
Netblock('192.168.0.0/24'), # site1 users
Netblock('10.0.0.0', 0xff000000), # site2 users
Netblock('192.168.99.0', '255.255.255.0'), # VPN users
'127.0.0.1', # localhost
])
>>> '192.168.1.24' in INTERNAL_IPS
True
>>> '31.41.59.26' in INTERNAL_IPS
False
>>> 'localhost' in INTERNAL_IPS
True
While the Django setting is called INTERNAL_IPS, it semantically
means "people who should see the inner workings of my code,
including possibly sensitive error messages", whereas the stuff
I've been working on is more for a decorator for my views:
@onsite_only
def my_view(request):
return render_to_response('internal_only.html')
(well, it's actually destined to become a middleware that adds an
"is_internal" to the request object based on the requester's IP
address)
Anyways, I don't know if it would be helpful stuff to integrate
into the project, but if anyone else is interested, I'd be glad
to share the module. It currently only works with IPv4, but I
don't yet toy with IPv6 so I don't know it enough to code for it.
-tim
We've been doing this for a while. It sounds like you have more
functionality in mind, though.
Hmm...your code seems to reference an "ipv4" module I don't have
here on either of my Debian boxes, or my Win32 box at work. That
could have been handy to have, rather than trying to reinvent the
wheel. The closest I could find was an entry in the Python
Cookbook that referenced an off-site broken-link. Anything that
works with the std library?
-tim
http://pypi.python.org/pypi/IPv4_Utils/0.35
It is apparently unmaintained, but does well enough. :)