"""
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
"""