ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
socket.cpp
Go to the documentation of this file.
1#include "socket.h"
2#if defined(USE_SOCKET_IMPL_LWIP_TCP) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS)
3#include <cerrno>
4#include <cstring>
5#include <string>
6#include "esphome/core/log.h"
8#ifdef USE_HOST
9#include "esphome/core/wake.h"
10#endif
11
12namespace esphome::socket {
13
14#ifdef USE_HOST
15// Host: ready when the wake select() loop has flagged this fd (or it isn't monitored).
16bool socket_ready_fd(int fd, bool loop_monitored) { return !loop_monitored || wake_fd_ready(fd); }
17#elif defined(USE_ZEPHYR)
18// Zephyr (nRF52): fd monitoring isn't wired into the esphome select loop
19// (wake_register_fd is USE_HOST-only), so loop_monitored is always false. Always
20// return true — the caller handles EAGAIN/EWOULDBLOCK on read.
21//
22// Cost (known trade-off, not an oversight): loop-monitored sockets (API, web_server)
23// are read every loop() iteration and bail on EAGAIN; there is no event-driven wake,
24// so the main loop busy-polls at loop frequency and cannot idle between packets.
25// TODO: wire Zephyr fds into an event-driven wake source (e.g. zsock_poll/k_poll) so
26// the loop can sleep between packets on battery/OpenThread targets.
27bool socket_ready_fd(int /*fd*/, bool /*loop_monitored*/) { return true; }
28#endif
29
30// Platform-specific inet_ntop wrappers
31#if defined(USE_SOCKET_IMPL_LWIP_TCP)
32// LWIP raw TCP (ESP8266) uses inet_ntoa_r which takes struct by value
33static inline const char *esphome_inet_ntop4(const void *addr, char *buf, size_t size) {
34 inet_ntoa_r(*reinterpret_cast<const struct in_addr *>(addr), buf, size);
35 return buf;
36}
37#if USE_NETWORK_IPV6
38static inline const char *esphome_inet_ntop6(const void *addr, char *buf, size_t size) {
39 inet6_ntoa_r(*reinterpret_cast<const ip6_addr_t *>(addr), buf, size);
40 return buf;
41}
42#endif
43#elif defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
44// LWIP sockets (LibreTiny, ESP32 Arduino)
45static inline const char *esphome_inet_ntop4(const void *addr, char *buf, size_t size) {
46 return lwip_inet_ntop(AF_INET, addr, buf, size);
47}
48#if USE_NETWORK_IPV6
49static inline const char *esphome_inet_ntop6(const void *addr, char *buf, size_t size) {
50 return lwip_inet_ntop(AF_INET6, addr, buf, size);
51}
52#endif
53#elif defined(USE_ZEPHYR)
54// Zephyr BSD sockets — use Zephyr native address formatting via POSIX-subset wrappers.
55// <zephyr/net/socket.h> is already included transitively through <sys/socket.h>.
56static inline const char *esphome_inet_ntop4(const void *addr, char *buf, size_t size) {
57 return zsock_inet_ntop(AF_INET, addr, buf, size);
58}
59// IPv6 is always enabled on nRF52 (config validation enforces enable_ipv6=True),
60// but the guard is retained for consistency with other platform blocks.
61#if USE_NETWORK_IPV6
62static inline const char *esphome_inet_ntop6(const void *addr, char *buf, size_t size) {
63 return zsock_inet_ntop(AF_INET6, addr, buf, size);
64}
65#endif
66#else
67// BSD sockets (host, ESP32-IDF)
68static inline const char *esphome_inet_ntop4(const void *addr, char *buf, size_t size) {
69 return inet_ntop(AF_INET, addr, buf, size);
70}
71#if USE_NETWORK_IPV6
72static inline const char *esphome_inet_ntop6(const void *addr, char *buf, size_t size) {
73 return inet_ntop(AF_INET6, addr, buf, size);
74}
75#endif
76#endif
77
78// Format sockaddr into caller-provided buffer, returns length written (excluding null)
79size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::span<char, SOCKADDR_STR_LEN> buf) {
80 if (addr_ptr->sa_family == AF_INET && len >= sizeof(const struct sockaddr_in)) {
81 const auto *addr = reinterpret_cast<const struct sockaddr_in *>(addr_ptr);
82 if (esphome_inet_ntop4(&addr->sin_addr, buf.data(), buf.size()) != nullptr)
83 return strlen(buf.data());
84 }
85#if USE_NETWORK_IPV6
86 else if (addr_ptr->sa_family == AF_INET6 && len >= sizeof(sockaddr_in6)) {
87 const auto *addr = reinterpret_cast<const struct sockaddr_in6 *>(addr_ptr);
88#ifdef USE_HOST
89 // Format IPv4-mapped IPv6 addresses as regular IPv4 (POSIX layout, no LWIP union)
90 if (IN6_IS_ADDR_V4MAPPED(&addr->sin6_addr) &&
91 esphome_inet_ntop4(&addr->sin6_addr.s6_addr[12], buf.data(), buf.size()) != nullptr) {
92 return strlen(buf.data());
93 }
94#elif defined(USE_ZEPHYR)
95 // Format IPv4-mapped IPv6 addresses as regular IPv4. Zephyr uses the standard POSIX
96 // s6_addr layout (not the LWIP union) but provides no IN6_IS_ADDR_V4MAPPED macro, so
97 // detect the ::ffff:0:0/96 prefix directly on the address words.
98 if (addr->sin6_addr.s6_addr32[0] == 0 && addr->sin6_addr.s6_addr32[1] == 0 &&
99 addr->sin6_addr.s6_addr32[2] == htonl(0xFFFF) &&
100 esphome_inet_ntop4(&addr->sin6_addr.s6_addr32[3], buf.data(), buf.size()) != nullptr) {
101 return strlen(buf.data());
102 }
103#elif !defined(USE_SOCKET_IMPL_LWIP_TCP)
104 // Format IPv4-mapped IPv6 addresses as regular IPv4 (LWIP layout)
105 if (addr->sin6_addr.un.u32_addr[0] == 0 && addr->sin6_addr.un.u32_addr[1] == 0 &&
106 addr->sin6_addr.un.u32_addr[2] == htonl(0xFFFF) &&
107 esphome_inet_ntop4(&addr->sin6_addr.un.u32_addr[3], buf.data(), buf.size()) != nullptr) {
108 return strlen(buf.data());
109 }
110#endif
111 if (esphome_inet_ntop6(&addr->sin6_addr, buf.data(), buf.size()) != nullptr)
112 return strlen(buf.data());
113 }
114#endif
115 buf[0] = '\0';
116 return 0;
117}
118
119std::unique_ptr<Socket> socket_ip(int type, int protocol) {
120#if USE_NETWORK_IPV6
121 return socket(AF_INET6, type, protocol);
122#else
123 return socket(AF_INET, type, protocol);
124#endif /* USE_NETWORK_IPV6 */
125}
126
127#ifdef USE_SOCKET_IMPL_LWIP_TCP
128// LWIP_TCP has separate Socket/ListenSocket types — needs out-of-line factory.
129// BSD and LWIP_SOCKETS define this inline in socket.h.
130std::unique_ptr<ListenSocket> socket_ip_loop_monitored(int type, int protocol) {
131#if USE_NETWORK_IPV6
132 return socket_listen_loop_monitored(AF_INET6, type, protocol);
133#else
134 return socket_listen_loop_monitored(AF_INET, type, protocol);
135#endif /* USE_NETWORK_IPV6 */
136}
137#endif
138
139socklen_t set_sockaddr(struct sockaddr *addr, socklen_t addrlen, const char *ip_address, uint16_t port) {
140#if USE_NETWORK_IPV6
141 if (strchr(ip_address, ':') != nullptr) {
142 if (addrlen < sizeof(sockaddr_in6)) {
143 errno = EINVAL;
144 return 0;
145 }
146 auto *server = reinterpret_cast<sockaddr_in6 *>(addr);
147 memset(server, 0, sizeof(sockaddr_in6));
148 server->sin6_family = AF_INET6;
149 server->sin6_port = htons(port);
150
151#ifdef USE_SOCKET_IMPL_BSD_SOCKETS
152#if defined(USE_ZEPHYR)
153 // Zephyr BSD sockets: use native address conversion
154 if (zsock_inet_pton(AF_INET6, ip_address, &server->sin6_addr) != 1) {
155 errno = EINVAL;
156 return 0;
157 }
158#else
159 // Use standard inet_pton for BSD sockets
160 if (inet_pton(AF_INET6, ip_address, &server->sin6_addr) != 1) {
161 errno = EINVAL;
162 return 0;
163 }
164#endif
165#else
166 // Use LWIP-specific functions
167 ip6_addr_t ip6;
168 inet6_aton(ip_address, &ip6);
169 memcpy(server->sin6_addr.un.u32_addr, ip6.addr, sizeof(ip6.addr));
170#endif
171 return sizeof(sockaddr_in6);
172 }
173#endif /* USE_NETWORK_IPV6 */
174 if (addrlen < sizeof(sockaddr_in)) {
175 errno = EINVAL;
176 return 0;
177 }
178 auto *server = reinterpret_cast<sockaddr_in *>(addr);
179 memset(server, 0, sizeof(sockaddr_in));
180 server->sin_family = AF_INET;
181#if defined(USE_ZEPHYR)
182 // Zephyr BSD sockets: use native address conversion
183 if (zsock_inet_pton(AF_INET, ip_address, &server->sin_addr) != 1) {
184 errno = EINVAL;
185 return 0;
186 }
187#else
188 server->sin_addr.s_addr = inet_addr(ip_address);
189#endif
190 server->sin_port = htons(port);
191 return sizeof(sockaddr_in);
192}
193
194socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port) {
195#if USE_NETWORK_IPV6
196 if (addrlen < sizeof(sockaddr_in6)) {
197 errno = EINVAL;
198 return 0;
199 }
200 auto *server = reinterpret_cast<sockaddr_in6 *>(addr);
201 memset(server, 0, sizeof(sockaddr_in6));
202 server->sin6_family = AF_INET6;
203 server->sin6_port = htons(port);
204 server->sin6_addr = IN6ADDR_ANY_INIT;
205 return sizeof(sockaddr_in6);
206#else
207 if (addrlen < sizeof(sockaddr_in)) {
208 errno = EINVAL;
209 return 0;
210 }
211 auto *server = reinterpret_cast<sockaddr_in *>(addr);
212 memset(server, 0, sizeof(sockaddr_in));
213 server->sin_family = AF_INET;
214 server->sin_addr.s_addr = ESPHOME_INADDR_ANY;
215 server->sin_port = htons(port);
216 return sizeof(sockaddr_in);
217#endif /* USE_NETWORK_IPV6 */
218}
219} // namespace esphome::socket
220#endif
uint16_t type
uint32_t socklen_t
Definition headers.h:99
struct in6_addr ip6_addr_t
Definition ip_address.h:24
socklen_t set_sockaddr(struct sockaddr *addr, socklen_t addrlen, const char *ip_address, uint16_t port)
Set a sockaddr to the specified address and port for the IP version used by socket_ip().
Definition socket.cpp:139
std::unique_ptr< Socket > socket_ip(int type, int protocol)
Create a socket in the newest available IP domain (IPv6 or IPv4) of the given type and protocol.
Definition socket.cpp:119
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)
Definition socket.cpp:79
std::unique_ptr< ListenSocket > socket_listen_loop_monitored(int domain, int type, int protocol)
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.
bool socket_ready_fd(int fd, bool loop_monitored)
Shared ready() helper for fd-based socket implementations.
Definition socket.cpp:16
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
Definition socket.cpp:194
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.cpp:130
bool ESPHOME_ALWAYS_INLINE wake_fd_ready(int fd)
Definition wake_host.h:42
const void size_t len
Definition hal.h:64
uint16_t size
Definition helpers.cpp:25
sa_family_t sa_family
Definition headers.h:87
Platform-specific main loop wake primitives.