Login

Test IP against IP address+Subnet whitelist

Author:
mtigas
Posted:
July 10, 2009
Language:
Python
Version:
1.0
Tags:
ip-address whitelist ipaddr subnet
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. Storing IP address ModelField as Integer, without nasty hacks.. by sleepycal 3 years, 10 months ago
  2. Globs for INTERNAL_IPS by kcarnold 6 years, 2 months ago
  3. Include entire networks in INTERNAL_IPS setting by pmclanahan 6 years, 2 months ago
  4. Sanitize HTML filter with tag/attribute whitelist and XSS protection by harrym 5 years, 10 months ago
  5. User/IP Banning Middleware by justquick 7 years ago

Comments

Please login first before commenting.