IpHelper.cs 925 B

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. namespace RackPeek.Domain.Resources.Services.Networking;
  3. public static class IpHelper
  4. {
  5. public static uint ToUInt32(string ip)
  6. {
  7. var parts = ip.Split('.');
  8. if (parts.Length != 4)
  9. throw new ArgumentException($"Invalid IPv4 address: {ip}");
  10. return (uint)(
  11. (int.Parse(parts[0]) << 24) |
  12. (int.Parse(parts[1]) << 16) |
  13. (int.Parse(parts[2]) << 8) |
  14. int.Parse(parts[3]));
  15. }
  16. public static string ToIp(uint ip)
  17. {
  18. return string.Join('.',
  19. (ip >> 24) & 0xFF,
  20. (ip >> 16) & 0xFF,
  21. (ip >> 8) & 0xFF,
  22. ip & 0xFF);
  23. }
  24. public static uint MaskFromPrefix(int prefix)
  25. {
  26. if (prefix < 0 || prefix > 32)
  27. throw new ArgumentException($"Invalid CIDR prefix: {prefix}");
  28. return prefix == 0 ? 0 : uint.MaxValue << (32 - prefix);
  29. }
  30. }