C#: IPv4 subnets with IPAddress and bit masks
An IPv4 address is 32 bits. In CIDR notation 192.168.10.77/26, the first 26 bits are the network part. The subnet mask has ones in those bits and zeros elsewhere. ANDing an address with the mask gives the network address, and setting all host bits to one gives the broadcast address.
C#
using System;
using System.Net;
class Program {
static uint ToNumber(string text) {
byte[] b = IPAddress.Parse(text).GetAddressBytes();
return ((uint)b[0] << 24) | ((uint)b[1] << 16) | ((uint)b[2] << 8) | b[3];
}
static string ToText(uint v) {
return new IPAddress(new[] { (byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v }).ToString();
}
static void Main() {
int prefix = 26;
uint mask = prefix == 0 ? 0 : uint.MaxValue << (32 - prefix);
uint network = ToNumber("192.168.10.77") & mask;
uint broadcast = network | ~mask;
Console.WriteLine("network " + ToText(network));
Console.WriteLine("broadcast " + ToText(broadcast));
Console.WriteLine("hosts " + ((1L << (32 - prefix)) - 2));
foreach (string candidate in new[] { "192.168.10.100", "192.168.10.130" }) {
bool inside = (ToNumber(candidate) & mask) == network;
Console.WriteLine(candidate + " in subnet: " + inside);
}
}
}