ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
ipv4_allow.cpp
Go to the documentation of this file.
1#include "ipv4_allow.h"
2
3#ifdef USE_SOCKET_IPV4_ALLOW
4
5#include "esphome/core/log.h"
6
7#include <span>
8
9namespace esphome::socket {
10
11bool Ipv4Allow::admit(const struct sockaddr *peer, socklen_t len, const char *tag, uint32_t now) {
12 if (this->allows(peer)) {
13 return true;
14 }
15 if (this->last_reject_log_ms_ == 0 || now - this->last_reject_log_ms_ >= REJECT_LOG_INTERVAL_MS) {
16 this->last_reject_log_ms_ = now;
17 char text[SOCKADDR_STR_LEN];
18 format_sockaddr_to(peer, len, std::span<char, SOCKADDR_STR_LEN>(text));
19 ESP_LOGW(tag, "Rejected %s", text);
20 }
21 return false;
22}
23
24void Ipv4Allow::dump_config(const char *tag) const {
25 for (size_t i = 0; i < this->count_; i++) {
26 const Ipv4AllowEntry e = this->entry(i);
27 // Network order is dotted order, and the contiguous mask's popcount is the prefix.
28 const auto *b = reinterpret_cast<const uint8_t *>(&e.addr);
29 ESP_LOGCONFIG(tag, " Allowed IP: %u.%u.%u.%u/%u", b[0], b[1], b[2], b[3],
30 static_cast<unsigned>(__builtin_popcount(e.mask)));
31 }
32}
33
34} // namespace esphome::socket
35
36#endif
Ipv4AllowEntry entry(size_t i) const
A copy of entry i, read from flash.
Definition ipv4_allow.h:56
void dump_config(const char *tag) const
One config line per allowed network.
bool allows(const struct sockaddr *peer) const
A v4 mapped IPv6 peer is unwrapped; any other family fails a non empty list.
Definition ipv4_allow.h:28
bool admit(const struct sockaddr *peer, socklen_t len, const char *tag, uint32_t now)
allows(peer), logging a refused peer at most once every REJECT_LOG_INTERVAL_MS.
static constexpr uint32_t REJECT_LOG_INTERVAL_MS
Definition ipv4_allow.h:63
uint32_t socklen_t
Definition headers.h:109
size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::span< char, SOCKADDR_STR_LEN > buf)
Format sockaddr into caller-provided buffer, returns length written (excluding null)
const void size_t len
Definition hal.h:68
static void uint32_t
One allowed IPv4 network, network byte order, host bits cleared.
Definition ipv4_allow.h:14
uint32_t mask
Definition ipv4_allow.h:16
uint32_t addr
Definition ipv4_allow.h:15