You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.4 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace EasyBL
  9. {
  10. public class IPAddressRange
  11. {
  12. readonly AddressFamily addressFamily;
  13. readonly byte[] lowerBytes;
  14. readonly byte[] upperBytes;
  15. public IPAddressRange(IPAddress lowerInclusive, IPAddress upperInclusive)
  16. {
  17. addressFamily = lowerInclusive.AddressFamily;
  18. lowerBytes = lowerInclusive.GetAddressBytes();
  19. upperBytes = upperInclusive.GetAddressBytes();
  20. }
  21. public bool IsInRange(IPAddress address)
  22. {
  23. if (address.AddressFamily != addressFamily)
  24. {
  25. return false;
  26. }
  27. var addressBytes = address.GetAddressBytes();
  28. bool lowerBoundary = true, upperBoundary = true;
  29. for (var i = 0; i < lowerBytes.Length &&
  30. (lowerBoundary || upperBoundary); i++)
  31. {
  32. if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) ||
  33. (upperBoundary && addressBytes[i] > upperBytes[i]))
  34. {
  35. return false;
  36. }
  37. lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
  38. upperBoundary &= (addressBytes[i] == upperBytes[i]);
  39. }
  40. return true;
  41. }
  42. }
  43. }