Calculate IP range by subnet mask

前端 未结 4 1593
傲寒
傲寒 2020-12-31 20:12

If I have a subnet mask e.g. 255.255.255.0 and an ip address 192.168.1.5, is there an easy way to determine all the possible ip addresses within th

4条回答
  •  难免孤独
    2020-12-31 20:28

    10 minutes of coding, and NOT fully tested:

    class IPSegment {
    
        private UInt32 _ip;
        private UInt32 _mask;
    
        public IPSegment(string ip, string mask) {
            _ip = ip.ParseIp();
            _mask = mask.ParseIp();
        }
    
        public UInt32 NumberOfHosts {
            get { return ~_mask+1; }
        }
    
        public UInt32 NetworkAddress {
            get { return _ip & _mask; }
        }
    
        public UInt32 BroadcastAddress {
            get { return NetworkAddress + ~_mask; }
        }
    
        public IEnumerable Hosts(){
            for (var host = NetworkAddress+1; host < BroadcastAddress; host++) {
                yield return  host;
            }
        }
    
    }
    
    public static class IpHelpers {
        public static string ToIpString(this UInt32 value) {
            var bitmask = 0xff000000;
            var parts = new string[4];
            for (var i = 0; i < 4; i++) {
                var masked = (value & bitmask) >> ((3-i)*8);
                bitmask >>= 8;
                parts[i] = masked.ToString(CultureInfo.InvariantCulture);
            }
            return String.Join(".", parts);
        }
    
        public static UInt32 ParseIp(this string ipAddress) {
            var splitted = ipAddress.Split('.');
            UInt32 ip = 0;
            for (var i = 0; i < 4; i++) {
                ip = (ip << 8) + UInt32.Parse(splitted[i]);
            }
            return ip;
        }
    }
    

    Usage:

        static void Main(string[] args) {
    
            IPSegment ip = new IPSegment("192.168.1.1","255.255.255.248");
    
            Console.WriteLine(ip.NumberOfHosts);
            Console.WriteLine(ip.NetworkAddress.ToIpString());
            Console.WriteLine(ip.BroadcastAddress.ToIpString());
    
            Console.WriteLine("===");
            foreach (var host in ip.Hosts()) {
                Console.WriteLine(host.ToIpString());
            }
            Console.ReadLine();
    
        }
    

提交回复
热议问题