CreateSubnetMaskIPv4() public static method

public static CreateSubnetMaskIPv4 ( byte cidr ) : IPAddress
cidr byte
return System.Net.IPAddress
コード例 #1
0
ファイル: IPRange.cs プロジェクト: hanswolff/ipranges
        public static bool TryParseNetwork(string network, out IPRange range, out Exception exception)
        {
            exception = null;
            range     = null;

            if (network == null)
            {
                exception = new ArgumentNullException("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 \"129.168.1.0/24\")", "network");
                return(false);
            }

            IPAddress networkIp;

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

            byte cidr;

            if (!Byte.TryParse(network.Substring(pos + 1), out cidr))
            {
                exception = new ArgumentException("Cannot parse CIDR part of IP address", "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);
        }