# How to determine largest cidr in a range of IPs

Say I've got a begin ip and an end ip. What would be the easiest way to figure out the largest cidr I could allocate from this range in order to reduce fragmentation?

For example, I have the range 10.10.1.0 - 10.10.2.128.

I request a /25. The easiest algorithm would give me 10.10.1.0/25 and be done with it, but then this fragments the /24 and doesn't allocate the /25 (10.10.2.0/25). What I would like to see is to allocate the 10.10.2.0/25 and leave 10.10.1.0-10.10.1.255 untouched.

Any ideas would be welcome. Been beating my head over this for a bit.

-

It sounds like you want something close to the buddy allocator, to borrow a page (ha ha) from memory management.

Step 1: Transform the range you have into a series of CIDR blocks that are as large as possible without crossing the range boundary or overlapping with another block.

Step 2: Given the allocation you're trying to fit, find the smallest possible block that will fit it. Ideally this will match it exactly, but if not, you will split up the smallest block you did find (potentially recursively) until you're at the right size block.

My wording isn't particularly elegant here but I hope you get the idea.

-
This is exactly what I am trying to do, but I am a bit confused on the bit math that would break down the large block into a series of blocks. Will have to bang away a bit more tomorrow. :) – Magic Hat Aug 11 '10 at 23:15
Start by enumerating all of the /32s in the range. For each /32, push it onto a stack, then attempt to merge the top two allocations in the stack (contingent upon them being the same size and valid after being merged). If it works, repeat this step until it doesn't work. After this enumeration is complete, the stack should contain what you want. Unless I missed something, which is entirely possible. – Drew Bloechl Aug 11 '10 at 23:38
I'll give this a shot and see how it plays out. Thanks Drew. – Magic Hat Aug 12 '10 at 13:25

There is not a CIDR that is bounded by 10.10.1.0 - 10.10.2.128

10.10.1.0 /22 is 10.10.0.0 - 10.10.3.255

10.10.1.0 /23 is 10.10.0.0 - 10.10.1.255

10.10.1.0 /24 is 10.10.1.0 - 10.10.1.255

You could have two separate networks:

10.10.1.0 /24 is 10.10.1.0 - 10.10.1.255

10.10.2.0 /25 is 10.10.2.0 - 10.10.2.127

-
Downvote on six year old post without a comment as to why. Nice! – dbasnett May 13 at 14:19