IPAddress.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include "IPAddress.h"
  2. #include <string.h>
  3. #include "Debug.h"
  4. IPAddress::IPAddress(const char *ip,int length)
  5. {
  6. IP = new char[length+1];
  7. if (IP != nullptr) {
  8. memcpy(IP,ip,length);
  9. IP[length] = 0;
  10. Length = length;
  11. } else {
  12. Length = 0;
  13. }
  14. }
  15. IPAddress::IPAddress()
  16. {
  17. IP = nullptr;
  18. Length = 0;
  19. }
  20. IPAddress& IPAddress::operator=(const char *ip)
  21. {
  22. int length = (ip == nullptr ? 0 : strlen(ip));
  23. if (length == 0) {
  24. Clear();
  25. } else {
  26. // Try to reuse the existing buffer if possible.
  27. if ((Length > 0) && (Length < length)) {
  28. Clear();
  29. }
  30. if (IP == nullptr) {
  31. IP = new char[length+1];
  32. }
  33. if (IP != nullptr) {
  34. memcpy(IP,ip,length);
  35. IP[length] = 0;
  36. Length = length;
  37. }
  38. }
  39. return *this;
  40. }
  41. IPAddress& IPAddress::operator=(IPAddress& other)
  42. {
  43. // Guard self assignment
  44. if (this == &other)
  45. {
  46. return *this; // delete[]/size=0 would also be ok
  47. }
  48. Clear();
  49. IP = other.IP;
  50. Length = other.Length;
  51. other.IP = nullptr;
  52. other.Length = 0;
  53. return *this;
  54. }
  55. IPAddress::~IPAddress()
  56. {
  57. Clear();
  58. }
  59. void IPAddress::Clear()
  60. {
  61. if (IP != nullptr) {
  62. delete[] IP;
  63. IP = nullptr;
  64. Length = 0;
  65. }
  66. }
  67. int IPAddress::Compare(IPAddress *first,IPAddress *second)
  68. {
  69. bool firstIsNull = ((first == nullptr) || (first->IP == nullptr));
  70. bool secondIsNull = ((second == nullptr) || (second->IP == nullptr));
  71. if (firstIsNull) {
  72. return secondIsNull ? 0 : -1;
  73. }
  74. if (secondIsNull) {
  75. return 1;
  76. }
  77. // Don't do a string compare if they're different lengths because this is just for a binary tree.
  78. int compare = first->Length - second->Length;
  79. if (compare == 0)
  80. {
  81. compare = memcmp(first->IP,second->IP,first->Length);
  82. }
  83. return compare;
  84. }
  85. // Is this an IP address? You can't trust the database because it might have been hacked.
  86. bool IPAddress::IsIP(const char *ip)
  87. {
  88. const char *loop;
  89. char ch;
  90. if (ip == nullptr) {
  91. return false;
  92. }
  93. if (*ip == 0) {
  94. return false;
  95. }
  96. loop = ip;
  97. while(true)
  98. {
  99. ch = *(loop++);
  100. if (ch == 0) {
  101. break;
  102. }
  103. if ((ch != '.') && ((ch < '0') || (ch > '9'))) {
  104. return false;
  105. }
  106. }
  107. return true;
  108. }