ESPHome  2023.8.3
ip_address.h
Go to the documentation of this file.
1 #pragma once
2 #include <cstdint>
3 #include <string>
4 #include <cstdio>
5 #include <array>
6 
7 namespace esphome {
8 namespace network {
9 
10 struct IPAddress {
11  public:
12  IPAddress() : addr_({0, 0, 0, 0}) {}
13  IPAddress(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) : addr_({first, second, third, fourth}) {}
14  IPAddress(uint32_t raw) {
15  addr_[0] = (uint8_t) (raw >> 0);
16  addr_[1] = (uint8_t) (raw >> 8);
17  addr_[2] = (uint8_t) (raw >> 16);
18  addr_[3] = (uint8_t) (raw >> 24);
19  }
20  operator uint32_t() const {
21  uint32_t res = 0;
22  res |= ((uint32_t) addr_[0]) << 0;
23  res |= ((uint32_t) addr_[1]) << 8;
24  res |= ((uint32_t) addr_[2]) << 16;
25  res |= ((uint32_t) addr_[3]) << 24;
26  return res;
27  }
28  std::string str() const {
29  char buffer[24];
30  snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d", addr_[0], addr_[1], addr_[2], addr_[3]);
31  return buffer;
32  }
33  bool operator==(const IPAddress &other) const {
34  return addr_[0] == other.addr_[0] && addr_[1] == other.addr_[1] && addr_[2] == other.addr_[2] &&
35  addr_[3] == other.addr_[3];
36  }
37  uint8_t operator[](int index) const { return addr_[index]; }
38  uint8_t &operator[](int index) { return addr_[index]; }
39 
40  protected:
41  std::array<uint8_t, 4> addr_;
42 };
43 
44 } // namespace network
45 } // namespace esphome
std::array< uint8_t, 4 > addr_
Definition: ip_address.h:41
uint8_t raw[35]
Definition: bl0939.h:19
bool operator==(const IPAddress &other) const
Definition: ip_address.h:33
std::string str() const
Definition: ip_address.h:28
uint8_t & operator[](int index)
Definition: ip_address.h:38
IPAddress(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth)
Definition: ip_address.h:13
uint8_t operator[](int index) const
Definition: ip_address.h:37