using System.Collections.Generic; namespace DTS.Common.Utils { public class IPRange { /// /// ip range, or a start and a stop /// public IPAddressIntForm RangeStart { get; set; } public IPAddressIntForm RangeEnd { get; set; } public IPRange(IPAddressIntForm start, IPAddressIntForm end) { RangeStart = start; RangeEnd = end; } } /// /// just structure for ips broken into bytes /// public class IPAddressIntForm { public int ByteOne { get; } public int ByteTwo { get; } public int ByteThree { get; } public int ByteFour { get; } public IPAddressIntForm(int b1, int b2, int b3, int b4) { ByteOne = b1; ByteTwo = b2; ByteThree = b3; ByteFour = b4; } public override string ToString() { return $"{ByteOne}.{ByteTwo}.{ByteThree}.{ByteFour}"; } public static bool TryParse(string input, out IPAddressIntForm output) { var tokens = input.Split('.'); if (4 != tokens.Length) { output = null; return false; } if (int.TryParse(tokens[0], out int one) && int.TryParse(tokens[1], out int two) && int.TryParse(tokens[2], out int three) && int.TryParse(tokens[3], out int four)) { output = new IPAddressIntForm(one, two, three, four); return true; } else { output = null; return false; } } internal class IPComparer : IComparer { public int Compare(IPAddressIntForm x, IPAddressIntForm y) { if (x == y) { return 0; } if (null == x) { return -1; } if (null == y) { return 1; } var ret = x.ByteOne.CompareTo(y.ByteOne); if (ret != 0) { return ret; } ret = x.ByteTwo.CompareTo(y.ByteTwo); if (ret != 0) { return ret; } ret = x.ByteThree.CompareTo(y.ByteThree); if (ret != 0) { return ret; } ret = x.ByteFour.CompareTo(y.ByteFour); if (ret != 0) { return ret; } return 0; } } /// /// gets all ips between a start and an end /// /// /// /// public static string[] GetAllIPs(IPAddressIntForm a, IPAddressIntForm b) { var list = new List(); var comparer = new IPComparer(); IPAddressIntForm start = a; IPAddressIntForm end = b; if (comparer.Compare(a, b) > 0) { start = b; end = a; } for( var firstByte = start.ByteOne; firstByte <= end.ByteOne; firstByte ++) { for( var secondByte = start.ByteTwo; secondByte <= end.ByteTwo; secondByte ++) { for ( var thirdByte = start.ByteThree; thirdByte <= end.ByteThree; thirdByte ++) { for ( var fourthByte = start.ByteFour; fourthByte <= end.ByteFour; fourthByte ++) { list.Add($"{firstByte}.{secondByte}.{thirdByte}.{fourthByte}"); } } } } return list.ToArray(); } } }