IP4.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #pragma once
  2. #include "common.h"
  3. #include <WiFi.h>
  4. #include <lwip/inet.h>
  5. #include <esp_wifi.h>
  6. //
  7. // There are no less than 3 different types for IP addresses used
  8. // by different APIs. This class attempts to unify them to mask the
  9. // differences.
  10. //
  11. class IP4 {
  12. private:
  13. union {
  14. uint8_t b[4];
  15. uint32_t l;
  16. };
  17. public:
  18. constexpr IP4() : l{0} { }
  19. constexpr IP4(nullptr_t) : l{0} { }
  20. constexpr IP4(int ll) : l{(uint32_t)ll} { }
  21. constexpr IP4(uint32_t ll) : l{ll} { }
  22. constexpr IP4(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) :
  23. b{b0,b1,b2,b3} { }
  24. IP4(const IPAddress & ip) : l{ip} { }
  25. constexpr IP4(const ip_addr_t & ip) :
  26. l{ip.type == IPADDR_TYPE_V4 ? ip.u_addr.ip4.addr : 0} { }
  27. constexpr IP4(const esp_ip_addr_t & ip) :
  28. l{ip.type == IPADDR_TYPE_V4 ? ip.u_addr.ip4.addr : 0} { }
  29. IP4(const char *str);
  30. constexpr operator uint32_t () { return l; }
  31. operator IPAddress () { return IPAddress(l); }
  32. constexpr operator ip_addr_t () {
  33. return ip_addr_t {
  34. .u_addr = {.ip4 = {.addr = l}},
  35. .type = IPADDR_TYPE_V4
  36. };
  37. }
  38. constexpr operator esp_ip_addr_t () {
  39. return esp_ip_addr_t {
  40. .u_addr = {.ip4 = {.addr = l}},
  41. .type = IPADDR_TYPE_V4
  42. };
  43. }
  44. constexpr operator bool () { return l != 0; }
  45. constexpr bool operator ! () { return l == 0; }
  46. constexpr bool operator == (const IP4 &b) { return l == b.l; }
  47. constexpr bool operator != (const IP4 &b) { return l != b.l; }
  48. constexpr uint8_t operator [] (size_t n) { return b[n]; }
  49. uint8_t & operator [] (size_t n) { return b[n]; }
  50. const char *cstr();
  51. };
  52. constexpr IP4 null_ip(0);