Skip to content

Instantly share code, notes, and snippets.

@JC3
Created May 30, 2021 17:56
Show Gist options
  • Save JC3/ce9b597445dc1196a827eba3754500e5 to your computer and use it in GitHub Desktop.
Save JC3/ce9b597445dc1196a827eba3754500e5 to your computer and use it in GitHub Desktop.
C# Parse CIDR IP address and mask
// quick and dirty, not very strict (accepts ipv6 on either side, and dotless ipv4)
static (IPAddress address, IPAddress mask) ParseCIDR (string str) {
string[] parts = str.Split('/');
if (parts.Length > 2)
throw new FormatException("Invalid CIDR string.");
else if (parts.Length == 1)
return (IPAddress.Parse(parts[0]), IPAddress.Broadcast);
else if (int.TryParse(parts[1], out int maskbits) && maskbits >= 0 && maskbits <= 32)
return (IPAddress.Parse(parts[0]), new IPAddress(0xFFFFFFFFL & IPAddress.HostToNetworkOrder(unchecked((int)0x80000000) >> (maskbits - 1))));
else
return (IPAddress.Parse(parts[0]), IPAddress.Parse(parts[1]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment