ESPHome  2022.12.8
socket.cpp
Go to the documentation of this file.
1 #include "socket.h"
2 #include "esphome/core/log.h"
3 #include <cstring>
4 #include <cerrno>
5 
6 namespace esphome {
7 namespace socket {
8 
9 std::unique_ptr<Socket> socket_ip(int type, int protocol) {
10 #if LWIP_IPV6
11  return socket(AF_INET6, type, protocol);
12 #else
13  return socket(AF_INET, type, protocol);
14 #endif
15 }
16 
17 socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port) {
18 #if LWIP_IPV6
19  if (addrlen < sizeof(sockaddr_in6)) {
20  errno = EINVAL;
21  return 0;
22  }
23  auto *server = reinterpret_cast<sockaddr_in6 *>(addr);
24  memset(server, 0, sizeof(sockaddr_in6));
25  server->sin6_family = AF_INET6;
26  server->sin6_port = port;
27  server->sin6_addr = in6addr_any;
28  return sizeof(sockaddr_in6);
29 #else
30  if (addrlen < sizeof(sockaddr_in)) {
31  errno = EINVAL;
32  return 0;
33  }
34  auto *server = reinterpret_cast<sockaddr_in *>(addr);
35  memset(server, 0, sizeof(sockaddr_in));
36  server->sin_family = AF_INET;
37  server->sin_addr.s_addr = ESPHOME_INADDR_ANY;
38  server->sin_port = port;
39  return sizeof(sockaddr_in);
40 #endif
41 }
42 } // namespace socket
43 } // namespace esphome
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:9
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address for the IP version used by socket_ip().
Definition: socket.cpp:17
uint32_t socklen_t
Definition: headers.h:86
uint8_t type
Definition: a4988.cpp:4
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.