/// <summary> /// Parses an address. Returns false and sets the <paramref name="cidr"/> to null if the parse fails. /// </summary> /// <param name="address"></param> /// <param name="cidr"></param> /// <returns></returns> public static bool TryParse(string address, out Cidr cidr) { var result = true; try { cidr = Parse(address); } catch { cidr = null; result = false; } return(result); }
/// <summary> /// Creates a new object. /// </summary> /// <param name="cidr"></param> public ByteArrayComparable(Cidr cidr) { if (cidr == null) { Array = _Empty; } else { var addressBytes = cidr.MaskedAddress.GetAddressBytes(); Array = new byte[addressBytes.Length + 1]; addressBytes.CopyTo(Array, 0); Array[Array.Length - 1] = (byte)cidr.BitmaskBits; } }
/// <summary> /// Parses an address. Throws exceptions if the parse fails. /// </summary> /// <param name="address"></param> /// <returns></returns> public static Cidr Parse(string address) { var result = new Cidr(); if (!String.IsNullOrEmpty(address)) { // IPAddress.Parse is quite happy with addresses like "1" - this just makes sure that we // have something that resembles a dotted-quad if (address.Count(r => r == '.') != 3) { throw new ArgumentException("Invalid IPv4 address", "address"); } var ipAddress = address; var bitmask = 32; var slashPosn = address.IndexOf('/'); if (slashPosn != -1) { ipAddress = address.Substring(0, slashPosn).Trim(); bitmask = int.Parse(address.Substring(slashPosn + 1)); } if (bitmask < 0 || bitmask > 32) { throw new ArgumentOutOfRangeException("The number of bits must be between 0 and 32 inclusive"); } result.BitmaskBits = bitmask; var clearBits = 32 - bitmask; while (bitmask-- != 0) { result.IPv4Bitmask = (result.IPv4Bitmask << 1) | 1; } result.IPv4Bitmask = result.IPv4Bitmask << clearBits; result.Address = IPAddress.Parse(ipAddress); if (result.Address.AddressFamily != AddressFamily.InterNetwork) { throw new InvalidOperationException("Only IPv4 addresses are currently supported"); } result._MaskedAddressBytes = ApplyBitmask(result.Address, result.IPv4Bitmask); result.MaskedAddress = new IPAddress(result._MaskedAddressBytes); } return(result); }