/// <summary> /// Constructs a subnet from an IPv4 address and subnet mask. /// </summary> /// <param name="address">The IP address.</param> /// <param name="subnetMask">The subnet mask.</param> public NetworkCidr(IPAddress address, IPAddress subnetMask) { Covenant.Requires <ArgumentNullException>(address != null, nameof(address)); Covenant.Requires <ArgumentException>(address.AddressFamily == AddressFamily.InterNetwork, nameof(address)); Covenant.Requires <ArgumentNullException>(subnetMask != null, nameof(subnetMask)); Covenant.Requires <ArgumentException>(subnetMask.AddressFamily == AddressFamily.InterNetwork, nameof(subnetMask)); // Count the number of zero bits from the least significant bit to // the first non-zero bit. var mask = NetHelper.AddressToUint(subnetMask); for (var position = 0; position < 32; position++) { if ((mask & (1 << position)) != 0) { // Ensure that the remaining mask bits are all ones. for (int i = position + 1; i < 32; i++) { if ((mask & (1 << i)) == 0) { throw new ArgumentException($"Subnet mask [{subnetMask}] is not valid because it has zero bits in the prefix."); } } Initialize(address, 32 - position); return; } } Initialize(address, 0); }
/// <summary> /// Initializes the instance. /// </summary> /// <param name="address">The IP address.</param> /// <param name="prefixLength">The network prefix mask length in bits.</param> private void Initialize(IPAddress address, int prefixLength) { PrefixLength = prefixLength; var maskBits = new Bits(32); for (int i = 0; i < prefixLength; i++) { maskBits[i] = true; } Mask = new IPAddress(maskBits.ToBytes()); Address = NetHelper.UintToAddress(NetHelper.AddressToUint(address) & NetHelper.AddressToUint(Mask)); }
/// <summary> /// Determines whether this subnet overlaps another. /// </summary> /// <param name="subnet">The subnet being tested.</param> /// <returns><c>true</c> if the subnets overlap.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="subnet"/> is <c>null</c>.</exception> public bool Overlaps(NetworkCidr subnet) { Covenant.Requires <ArgumentNullException>(subnet != null); var first = NetHelper.AddressToUint(this.FirstAddress); var last = NetHelper.AddressToUint(this.LastAddress); var subnetFirst = NetHelper.AddressToUint(subnet.FirstAddress); var subnetLast = NetHelper.AddressToUint(subnet.LastAddress); if (last < subnetFirst) { return(false); } else if (first > subnetLast) { return(false); } else { return(true); } }