Created
May 30, 2021 17:56
-
-
Save JC3/ce9b597445dc1196a827eba3754500e5 to your computer and use it in GitHub Desktop.
C# Parse CIDR IP address and mask
This file contains 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
// 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