Skip to content

Instantly share code, notes, and snippets.

@RobThree
Last active June 14, 2023 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobThree/9208f2548057438acaca6dcab95f6732 to your computer and use it in GitHub Desktop.
Save RobThree/9208f2548057438acaca6dcab95f6732 to your computer and use it in GitHub Desktop.
Calculate number of subnets of a given size you can 'create' or 'take' or 'extract' from a given network.
using System;
public class Program
{
public static void Main()
{
// Example: How many /30's can we fit in a /28?
var sourcePrefixLength = 28;
var destinationPrefixLength = 30;
Console.WriteLine(CalculateNumberOfSubnets(sourcePrefixLength, destinationPrefixLength));
}
// This method works for IPv4 and IPv6
public static UInt128 CalculateNumberOfSubnets(int sourcePrefixLength, int destinationPrefixLength)
=> sourcePrefixLength > destinationPrefixLength ? throw new Exception("Source prefix length must be less than, or equal to, destination prefix length")
: sourcePrefixLength > 128 || destinationPrefixLength > 128 ? throw new Exception("Prefix length cannot be greater than 128")
: sourcePrefixLength < 0 || destinationPrefixLength < 0 ? throw new Exception("Prefix length cannot be negative")
: destinationPrefixLength - sourcePrefixLength == 128 ? UInt128.MaxValue // Handle edge case
: (UInt128)1 << destinationPrefixLength - sourcePrefixLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment