public int GetPrefixLength() { byte[] byteBegin = Begin.GetAddressBytes(); byte[] byteEnd = End.GetAddressBytes(); // Handle single IP if (Begin.Equals(End)) { return(byteBegin.Length * 8); } int length = byteBegin.Length * 8; for (int i = 0; i < length; i++) { byte[] mask = Bits.GetBitMask(byteBegin.Length, i); if (new IPAddress(Bits.And(byteBegin, mask)).Equals(Begin)) { if (new IPAddress(Bits.Or(byteBegin, Bits.Not(mask))).Equals(End)) { return(i); } } } throw new FormatException(string.Format("{0} is not a CIDR Subnet", ToString())); }
/// <summary> /// Create a new range from a begin and end address. /// Throws an exception if Begin comes after End, or the /// addresses are not in the same family. /// </summary> public IPAddressRange(IPAddress begin, IPAddress end) { if (begin == null) { throw new ArgumentNullException("begin"); } if (end == null) { throw new ArgumentNullException("end"); } Begin = begin; End = end; if (Begin.AddressFamily != End.AddressFamily) { throw new ArgumentException("Elements must be of the same address family", "beginEnd"); } var beginBytes = Begin.GetAddressBytes(); var endBytes = End.GetAddressBytes(); if (!Bits.LE(endBytes, beginBytes)) { throw new ArgumentException("Begin must be smaller than the End", "beginEnd"); } }
public bool Contains ( IPAddress address ) { byte[] bytes = address.GetAddressBytes(); return(Bits.GE(Begin.GetAddressBytes(), bytes) && Bits.LE(End.GetAddressBytes(), bytes)); }
public IEnumerator <IPAddress> GetEnumerator() { var first = Begin.GetAddressBytes(); var last = End.GetAddressBytes(); for (var ip = first; Bits.LtECore(ip, last); ip = Bits.Increment(ip)) { yield return(new IPAddress(ip)); } }
public bool Contains(IPAddress ipaddress) { if (ipaddress.AddressFamily != Begin.AddressFamily) { return(false); } var adrBytes = ipaddress.GetAddressBytes(); return(Bits.GE(Begin.GetAddressBytes(), adrBytes) && Bits.LE(End.GetAddressBytes(), adrBytes)); }
/// <summary> /// Create a new range from a begin and end address. /// Throws an exception if Begin comes after End, or the /// addresses are not in the same family. /// </summary> public IPAddressRange(IPAddress begin, IPAddress end) { Begin = begin; End = end; if (!IsInSameAddressFamily(Begin, End)) { throw new ArgumentException("Elements must be of the same address family", "beginEnd"); } var beginBytes = Begin.GetAddressBytes(); var endBytes = End.GetAddressBytes(); if (!Bits.LE(endBytes, beginBytes)) { throw new ArgumentException("Begin must be smaller than the End", "beginEnd"); } }