pythoninetaddress

How to check if an IP is contained in a network with python?


How do I check whether an IP is contained in a network with python?

Eg:

# pseudo code
IP('10.40.0.1').contained_in(CDIR('10.40.0.0/24)) == True

Solution

  • Using Python 3.3+ ipaddress

    >>> import ipaddress
    >>> ipaddress.ip_address('10.40.0.1') in ipaddress.ip_network('10.40.0.0/24')
    True
    >>> ipaddress.ip_address('10.40.2.1') in ipaddress.ip_network('10.40.0.0/24')
    False
    

    There's also backport of ipaddress.

    Using ipaddr

    >>> import ipaddr
    >>> ipaddr.IPAddress('10.40.0.1') in ipaddr.IPNetwork('10.40.0.0/24')
    True
    >>> ipaddr.IPAddress('10.40.2.1') in ipaddr.IPNetwork('10.40.0.0/24')
    False