PowerShell Function to Extract Subnet/CIDR for a Pair of IP Addresses

Well, this one is hyper-specific... but in case anyone else needs to do something similar, I figure that I should share!  As a tiny part of a much bigger project, one of my customers gave me a list of VLAN IDs and the IP Ranges that they want to use on each VLAN.  Unfortunately, that list did not include either Subnet Mask or CIDR values, so I had to work backwards from the given ranges to determine what would be an acceptable Subnet Mask.  This process involves some annoying binary math, so you know that I put together a script to do it for me!

I wrote the extract-CIDR function to accept two IP Addresses, and then to output the smallest subnet/CIDR that could contain those two IP Addresses (so they don't technically need to be the start and end of the range, but it's safer to use those two).  For example, if I give the script 192.168.0.1 and 192.168.0.254, I want to get back 192.168.0.0/24.  If I'm playing around with subnets though, I want to be able to give it 192.168.1.130 and 192.168.1.254 and get back 192.168.1.128/25.  So, here it is!

Use this function with this syntax: extract-CIDR -addressPair @(<Address 1>,<Address 2>)

It then converts those dotted notation addresses to binary and looks for binary digits that are identical between the two addresses.  It keeps going until it gets a miss, then counts the matches and uses that to figure out the CIDR value for a subnet that contains those two addresses.  It then uses that CIDR value to figure out what the start of that subnet must be and generates its output in the format of <subnet start>/<CIDR Value>.

If you want to check it out, the script is on my GitHub.  As always, this is intended for educational purposes and, while it worked for me in my circumstance, that is no guarantee that it'll work for you in yours.  You should carefully vet any scripts that you find on the internet before executing them.  Have fun!

Comments

Popular posts from this blog

PowerShell Sorting by Multiple Columns

Clone a Standard vSwitch from one ESXi Host to Another

Deleting Orphaned (AKA Zombie) VMDK Files