How can I determine if an ip address exists inside a cidr range in python?

I have a long list of cidr ip address ranges in my firewall. In some instances I need to determine if a specified IP address falls inside one of my cidr deny range rules.

If possible this should be written in python.

Example:

ip = "192.168.1.5"

cidrs = [ "10.10.10.0/24", "10.11.10.0/22", "192.168.1.0/20" ]

The code should give me "192.168.1.0/20".

Thanks

asked 06 Sep '11, 22:39

fox's gravatar image

fox ♦♦
800162527
accept rate: 37%


from netaddr import all matching cidrs

The netaddr module has a method that does exactly what you are asking.

>>> from netaddr import all_matching_cidrs
>>> all_matching_cidrs("212.11.70.34", ["192.168.0.0/24","212.11.64.0/19"] )
[IPNetwork('212.11.64.0/19')]

Here is the usage for this method:

>>> help(all_matching_cidrs)

Help on function all_matching_cidrs in module netaddr.ip:

all_matching_cidrs(ip, cidrs)
    Matches an IP address or subnet against a given sequence of IP addresses and subnets.

    @param ip: a single IP address or subnet.

    @param cidrs: a sequence of IP addresses and/or subnets.

    @return: all matching IPAddress and/or IPNetwork objects from the provided
    sequence, an empty list if there was no match.

Basically you provide an ip address as the first argument and a list of cidrs as the second argument. A list of hits are returned.

link

answered 06 Sep '11, 22:43

Russell%20Ballestrini's gravatar image

Russell Ball...
1.3k232937
accept rate: 43%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×7
×1
×1
×1
×1

Asked: 06 Sep '11, 22:39

Seen: 1,747 times

Last updated: 06 Sep '11, 22:43

powered by OSQA