bschaatsbergen / cidr

CLI to perform various actions on CIDR ranges
https://formulae.brew.sh/formula/cidr
MIT License
133 stars 9 forks source link

[Feature Request] merge CIDR ranges #108

Open hellodword opened 3 weeks ago

hellodword commented 3 weeks ago
$ cidr merge "10.0.0.0/8" --exclude "192.168.2.0/24, 10.4.0.0/16"  --exclude "10.6.0.0/16"   "192.168.0.0/16"
10.0.0.0/14
10.5.0.0/16
10.7.0.0/16
10.8.0.0/13
10.16.0.0/12
10.32.0.0/11
10.64.0.0/10
10.128.0.0/9
192.168.0.0/23
192.168.3.0/24
192.168.4.0/22
192.168.8.0/21
192.168.16.0/20
192.168.32.0/19
192.168.64.0/18
192.168.128.0/17

# or merging only
$ cidr merge "192.168.1.0/31" "192.168.1.2/32" "192.168.1.3/32"
192.168.1.0/30

It should be useful while people are configuring their firewall rules.

For example, AllowedIPs for wireguard^1.

What do you think?

Phaze228 commented 2 weeks ago

The last example, makes sense to me. You have three small subnets to merge into a subnet big enough to occupy them all. The first, I am stupid on. You're merging 10.0.0.0/8....with 192.168.0.0/16 but excluding 3 ranges? Or the range of 192.168.2.0/24 - 10.4.0.0/16? Either way, I'm lost as to how you generate that output. Because in my head, you're saying merge 10.0.0.0/8 with 192.168.0.0/16 Which would be 10.0.0.0/0 which would be the only way to "merge" those two addresses.

Could you elaborate the first one a bit better?

hellodword commented 2 weeks ago

The ranges to merge are 10.0.0.0/8 and 192.168.0.0/16. The other ranges are to be excluded from the merged range. Please consider this as a CIDR calculator that provides precise results rather than the largest possible range.

10.0.0.0/8 + 192.168.0.0/16 = [ 10.0.0.0/8, 192.168.0.0/16 ]

[ 10.0.0.0/8, 192.168.0.0/16 ] - [ 192.168.2.0/24, 10.4.0.0/16, 10.6.0.0/16 ] =  [ 10.0.0.0/14, 10.5.0.0/16, 10.7.0.0/16, 10.8.0.0/13, 10.16.0.0/12, 10.32.0.0/11, 10.64.0.0/10, 10.128.0.0/9, 192.168.0.0/23, 192.168.3.0/24, 192.168.4.0/22, 192.168.8.0/21, 192.168.16.0/20, 192.168.32.0/19, 192.168.64.0/18, 192.168.128.0/17 ]

I think the Wireguard AllowedIPs is a use case for this.