Files
DP44/Common/DTS.Common/Utils/IPUtils.cs
2026-04-17 14:55:32 -04:00

112 lines
3.8 KiB
C#

using System.Collections.Generic;
namespace DTS.Common.Utils
{
public class IPRange
{
/// <summary>
/// ip range, or a start and a stop
/// </summary>
public IPAddressIntForm RangeStart { get; set; }
public IPAddressIntForm RangeEnd { get; set; }
public IPRange(IPAddressIntForm start, IPAddressIntForm end)
{
RangeStart = start;
RangeEnd = end;
}
}
/// <summary>
/// just structure for ips broken into bytes
/// </summary>
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<IPAddressIntForm>
{
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;
}
}
/// <summary>
/// gets all ips between a start and an end
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static string[] GetAllIPs(IPAddressIntForm a, IPAddressIntForm b)
{
var list = new List<string>();
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();
}
}
}