Last active
June 14, 2023 23:47
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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