Beispiel #1
0
        /// <summary>
        /// Attempts to parse a subnet from CIDR notation in the form of <i>ip-address</i>/<i>prefix</i>,
        /// where <i>prefix</i> is the network prefix length in bits.
        /// </summary>
        /// <param name="input">The input string.</param>
        /// <param name="cidr">The parsed <see cref="NetworkCidr"/>.</param>
        /// <returns><c>true</c> if the operation was successful.</returns>
        public static bool TryParse(string input, out NetworkCidr cidr)
        {
            cidr = null;

            if (string.IsNullOrEmpty(input))
            {
                return(false);
            }

            var slashPos = input.IndexOf('/');

            if (slashPos <= 0)
            {
                return(false);
            }

            if (!IPAddress.TryParse(input.Substring(0, slashPos), out var address))
            {
                return(false);
            }

            if (!int.TryParse(input.Substring(slashPos + 1), out var prefixLength) || prefixLength < 0 || prefixLength > 32)
            {
                return(false);
            }

            cidr = new NetworkCidr();

            cidr.Initialize(address, prefixLength);

            return(true);
        }
Beispiel #2
0
        /// <summary>
        /// Parses a subnet from CIDR notation in the form of <i>ip-address</i>/<i>prefix</i>,
        /// where <i>prefix</i> is the network prefix length in bits.
        /// </summary>
        /// <param name="input">The input string.</param>
        /// <returns>The parsed <see cref="NetworkCidr"/>.</returns>
        /// <exception cref="ArgumentException">Thrown if the input is not correctly formatted.</exception>
        public static NetworkCidr Parse(string input)
        {
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(input));

            var slashPos = input.IndexOf('/');

            if (slashPos <= 0)
            {
                throw new ArgumentException($"Invalid CIDR [{input}].");
            }

            if (!IPAddress.TryParse(input.Substring(0, slashPos), out var address))
            {
                throw new ArgumentException($"Invalid CIDR [{input}].");
            }

            if (!int.TryParse(input.Substring(slashPos + 1), out var prefixLength) || prefixLength < 0 || prefixLength > 32)
            {
                throw new ArgumentException($"Invalid CIDR [{input}].");
            }

            var cidr = new NetworkCidr();

            cidr.Initialize(address, prefixLength);

            return(cidr);
        }