1 static void Main(string[] args)
2 {
3 IList<IPAddress> fromto = GetIPAddressInRange(IPAddress.Parse("192.168.1.3"), IPAddress.Parse("192.168.0.254"));
4 IList<IPAddress> ips = GetSubnetIPAddress(IPAddress.Parse("192.168.0.1"), IPAddress.Parse("255.255.255.240"));
5 }
6
7 private static List<IPAddress> GetIPAddressInRange(IPAddress ipv4from, IPAddress ipv4to)
8 {
9 List<IPAddress> result = new List<IPAddress>();
10 UInt32 uintIPFrom = ToUInt32(ipv4from);
11 UInt32 uintIPTo = ToUInt32(ipv4to);
12 UInt32 start = uintIPFrom > uintIPTo ? uintIPTo : uintIPFrom;
13 UInt32 end = uintIPFrom > uintIPTo ? uintIPFrom : uintIPTo;
14 for (UInt32 i = start; i <= end; i++)
15 {
16 result.Add(ToIPAddress(i));
17 }
18 return result;
19 }
20
21 private static List<IPAddress> GetSubnetIPAddress(IPAddress ipv4adress, IPAddress ipv4mask)
22 {
23 List<IPAddress> result = new List<IPAddress>();
24 UInt32 uintIP = ToUInt32(ipv4adress);
25 UInt32 uintMask = ToUInt32(ipv4mask);
26 if (!ValidNetmask(uintMask)) { return result; }
27 UInt32 cidr = BitsSet(uintMask);
28 UInt32 uintNetwork = uintIP & uintMask;
29 UInt32 uintBoardcast = uintNetwork + ~uintMask;
30 for (UInt32 i = uintNetwork + 1; i <= uintBoardcast - 1; i++)
31 {
32 result.Add(ToIPAddress(i));
33 }
34 return result;
35 }
36
37 private static bool ValidNetmask(UInt32 netmask)
38 {
39 long num = ~netmask & ((long)0xffffffffL);
40 return (((num + 1L) & num) == 0L);
41 }
42
43 private static UInt32 ToUInt32(IPAddress ipv4)
44 {
45 Byte[] addressBytes = ipv4.GetAddressBytes();
46 if (addressBytes.Length != 4)
47 {
48 throw new ArgumentException("Only accept IPv4.");
49 }
50 Array.Reverse(addressBytes);
51 uint num = BitConverter.ToUInt32(addressBytes, 0);
52 return num;
53 }
54
55 public static IPAddress ToIPAddress(uint ipaddress)
56 {
57 byte[] bytes = BitConverter.GetBytes(ipaddress);
58 Array.Reverse(bytes);
59 return new IPAddress(bytes);
60 }
61
62 private static UInt32 BitsSet(UInt32 netmask)
63 {
64 UInt32 num = netmask;
65 num -= (num >> 1) & 0x55555555;
66 num = (num & 0x33333333) + ((num >> 2) & 0x33333333);
67 num = (UInt32)((((num + (num >> 4)) & 0xf0f0f0f) * 0x1010101) >> 0x18);
68 return num;
69 }