IpHelper.cs 898 B

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