Login

Test IP against IP address+Subnet whitelist

Author:
mtigas
Posted:
July 10, 2009
Language:
Python
Version:
1.0
Score:
-1 (after 1 ratings)

Simple function that tests whether a given IP address is in a list of IP addresses or subnets.

Requires ipaddr. Comes with Python 2.7 or 3.1, downloadable here for earlier versions.

More info on ipaddr in Python 3.1 docs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Simple function that tests whether a given IP address is in a list of IP addresses or subnets.

Requires ipaddr. Comes with Python 2.7 or 3.1, downloadable for previous Python versions from:
    http://code.google.com/p/ipaddr-py/
    
More info on ipaddr:
    http://docs.python.org/dev/py3k/library/ipaddr.html
"""

from ipaddr import IPv4

# An AOL IP, djangoproject.com, and a Google range.
# You know what to do here.
WHITELIST = (
    '64.12.193.85',
    '64.207.133.18',
    '74.125.0.0/16'
)

def ip_in_whitelist(request_ip):
    # the long int version of the ip address
    user_ip = IPv4(request_ip).ip
    
    for whitelist_ip in WHITELIST:
        w_ip = IPv4(whitelist_ip)
        
        # if ip == the network's base IP (which is the case if we're giving it a straight IP with
        # no range suffix) OR if ip is within the subnet for the given range
        # (a machine's address in a subnet can't ever be the broadcast address so it's < not <=)
        if (user_ip == w_ip.network) or ((user_ip >= w_ip.network) and (user_ip < w_ip.broadcast)):
            # if match, return true (short circuits the rest of the function)
            return True
    return False

""" # simple doctest:
>>> ip_in_whitelist('127.0.0.1')
False
>>> ip_in_whitelist('64.207.133.18')
True
>>> ip_in_whitelist('74.125.0.0')
True
>>> ip_in_whitelist('74.125.231.0') # same range as previous example
True
>>> ip_in_whitelist('74.125.255.255') # broadcast addy for previous range, so invalid
False
"""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.