Beispiel #1
0
        public static bool TryParseNetwork(string network, out IPRange range, out Exception exception)
        {
            exception = null;
            range     = null;

            if (network == null)
            {
                exception = new ArgumentNullException(nameof(network));
                return(false);
            }
            network = network.Trim();

            IPAddress singleAddress;

            if (IPAddress.TryParse(network, out singleAddress))
            {
                range = new IPRange(singleAddress, singleAddress);
                return(true);
            }

            var pos = network.IndexOf('/');

            if (pos < 0)
            {
                exception = new ArgumentException("Expected CIDR notation is missing network (correct example would be \"192.168.1.0/24\")", nameof(network));
                return(false);
            }

            IPAddress networkIp;

            if (!IPAddress.TryParse(network.Substring(0, pos), out networkIp))
            {
                exception = new ArgumentException("Cannot parse network part of IP address", nameof(network));
                return(false);
            }

            byte cidr;

            if (!byte.TryParse(network.Substring(pos + 1), out cidr))
            {
                exception = new ArgumentException("Cannot parse CIDR part of IP address", nameof(network));
                return(false);
            }

            var subnetMask = networkIp.AddressFamily == AddressFamily.InterNetworkV6
                ? IPAddressHelper.CreateSubnetMaskIPv6(cidr)
                : IPAddressHelper.CreateSubnetMaskIPv4(cidr);

            var fromIp = IPAddressHelper.GetNetworkAddress(networkIp, subnetMask);
            var toIp   = IPAddressHelper.GetBroadcastAddress(networkIp, subnetMask);

            range = new IPRange(fromIp, toIp);

            return(true);
        }