IpHelper.cs 909 B

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