udp_multicast_example_main.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /* UDP MultiCast Send/Receive Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <string.h>
  8. #include <sys/param.h>
  9. #include "freertos/FreeRTOS.h"
  10. #include "freertos/task.h"
  11. #include "freertos/event_groups.h"
  12. #include "esp_system.h"
  13. #include "esp_wifi.h"
  14. #include "esp_event.h"
  15. #include "esp_log.h"
  16. #include "nvs_flash.h"
  17. #include "esp_netif.h"
  18. #include "protocol_examples_common.h"
  19. #include "lwip/err.h"
  20. #include "lwip/sockets.h"
  21. #include "lwip/sys.h"
  22. #include <lwip/netdb.h>
  23. /* The examples use simple configuration that you can set via
  24. project configuration.
  25. If you'd rather not, just change the below entries to strings with
  26. the config you want - ie #define UDP_PORT 3333
  27. */
  28. #define UDP_PORT CONFIG_EXAMPLE_PORT
  29. #define MULTICAST_LOOPBACK CONFIG_EXAMPLE_LOOPBACK
  30. #define MULTICAST_TTL CONFIG_EXAMPLE_MULTICAST_TTL
  31. #define MULTICAST_IPV4_ADDR CONFIG_EXAMPLE_MULTICAST_IPV4_ADDR
  32. #define MULTICAST_IPV6_ADDR CONFIG_EXAMPLE_MULTICAST_IPV6_ADDR
  33. #define LISTEN_ALL_IF EXAMPLE_MULTICAST_LISTEN_ALL_IF
  34. static const char *TAG = "multicast";
  35. #ifdef CONFIG_EXAMPLE_IPV4
  36. static const char *V4TAG = "mcast-ipv4";
  37. #endif
  38. #ifdef CONFIG_EXAMPLE_IPV6
  39. static const char *V6TAG = "mcast-ipv6";
  40. #endif
  41. #ifdef CONFIG_EXAMPLE_IPV4
  42. /* Add a socket, either IPV4-only or IPV6 dual mode, to the IPV4
  43. multicast group */
  44. static int socket_add_ipv4_multicast_group(int sock, bool assign_source_if)
  45. {
  46. struct ip_mreq imreq = { 0 };
  47. struct in_addr iaddr = { 0 };
  48. int err = 0;
  49. // Configure source interface
  50. #if LISTEN_ALL_IF
  51. imreq.imr_interface.s_addr = IPADDR_ANY;
  52. #else
  53. esp_netif_ip_info_t ip_info = { 0 };
  54. err = esp_netif_get_ip_info(get_example_netif(), &ip_info);
  55. if (err != ESP_OK) {
  56. ESP_LOGE(V4TAG, "Failed to get IP address info. Error 0x%x", err);
  57. goto err;
  58. }
  59. inet_addr_from_ip4addr(&iaddr, &ip_info.ip);
  60. #endif // LISTEN_ALL_IF
  61. // Configure multicast address to listen to
  62. err = inet_aton(MULTICAST_IPV4_ADDR, &imreq.imr_multiaddr.s_addr);
  63. if (err != 1) {
  64. ESP_LOGE(V4TAG, "Configured IPV4 multicast address '%s' is invalid.", MULTICAST_IPV4_ADDR);
  65. // Errors in the return value have to be negative
  66. err = -1;
  67. goto err;
  68. }
  69. ESP_LOGI(TAG, "Configured IPV4 Multicast address %s", inet_ntoa(imreq.imr_multiaddr.s_addr));
  70. if (!IP_MULTICAST(ntohl(imreq.imr_multiaddr.s_addr))) {
  71. ESP_LOGW(V4TAG, "Configured IPV4 multicast address '%s' is not a valid multicast address. This will probably not work.", MULTICAST_IPV4_ADDR);
  72. }
  73. if (assign_source_if) {
  74. // Assign the IPv4 multicast source interface, via its IP
  75. // (only necessary if this socket is IPV4 only)
  76. err = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &iaddr,
  77. sizeof(struct in_addr));
  78. if (err < 0) {
  79. ESP_LOGE(V4TAG, "Failed to set IP_MULTICAST_IF. Error %d", errno);
  80. goto err;
  81. }
  82. }
  83. err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  84. &imreq, sizeof(struct ip_mreq));
  85. if (err < 0) {
  86. ESP_LOGE(V4TAG, "Failed to set IP_ADD_MEMBERSHIP. Error %d", errno);
  87. goto err;
  88. }
  89. err:
  90. return err;
  91. }
  92. #endif /* CONFIG_EXAMPLE_IPV4 */
  93. #ifdef CONFIG_EXAMPLE_IPV4_ONLY
  94. static int create_multicast_ipv4_socket(void)
  95. {
  96. struct sockaddr_in saddr = { 0 };
  97. int sock = -1;
  98. int err = 0;
  99. sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  100. if (sock < 0) {
  101. ESP_LOGE(V4TAG, "Failed to create socket. Error %d", errno);
  102. return -1;
  103. }
  104. // Bind the socket to any address
  105. saddr.sin_family = PF_INET;
  106. saddr.sin_port = htons(UDP_PORT);
  107. saddr.sin_addr.s_addr = htonl(INADDR_ANY);
  108. err = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
  109. if (err < 0) {
  110. ESP_LOGE(V4TAG, "Failed to bind socket. Error %d", errno);
  111. goto err;
  112. }
  113. // Assign multicast TTL (set separately from normal interface TTL)
  114. uint8_t ttl = MULTICAST_TTL;
  115. setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(uint8_t));
  116. if (err < 0) {
  117. ESP_LOGE(V4TAG, "Failed to set IP_MULTICAST_TTL. Error %d", errno);
  118. goto err;
  119. }
  120. #if MULTICAST_LOOPBACK
  121. // select whether multicast traffic should be received by this device, too
  122. // (if setsockopt() is not called, the default is no)
  123. uint8_t loopback_val = MULTICAST_LOOPBACK;
  124. err = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP,
  125. &loopback_val, sizeof(uint8_t));
  126. if (err < 0) {
  127. ESP_LOGE(V4TAG, "Failed to set IP_MULTICAST_LOOP. Error %d", errno);
  128. goto err;
  129. }
  130. #endif
  131. // this is also a listening socket, so add it to the multicast
  132. // group for listening...
  133. err = socket_add_ipv4_multicast_group(sock, true);
  134. if (err < 0) {
  135. goto err;
  136. }
  137. // All set, socket is configured for sending and receiving
  138. return sock;
  139. err:
  140. close(sock);
  141. return -1;
  142. }
  143. #endif /* CONFIG_EXAMPLE_IPV4_ONLY */
  144. #ifdef CONFIG_EXAMPLE_IPV6
  145. static int create_multicast_ipv6_socket(void)
  146. {
  147. struct sockaddr_in6 saddr = { 0 };
  148. int netif_index;
  149. struct in6_addr if_inaddr = { 0 };
  150. struct ip6_addr if_ipaddr = { 0 };
  151. struct ipv6_mreq v6imreq = { 0 };
  152. int sock = -1;
  153. int err = 0;
  154. sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IPV6);
  155. if (sock < 0) {
  156. ESP_LOGE(V6TAG, "Failed to create socket. Error %d", errno);
  157. return -1;
  158. }
  159. // Bind the socket to any address
  160. saddr.sin6_family = AF_INET6;
  161. saddr.sin6_port = htons(UDP_PORT);
  162. bzero(&saddr.sin6_addr.un, sizeof(saddr.sin6_addr.un));
  163. err = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in6));
  164. if (err < 0) {
  165. ESP_LOGE(V6TAG, "Failed to bind socket. Error %d", errno);
  166. goto err;
  167. }
  168. // Selct the interface to use as multicast source for this socket.
  169. #if LISTEN_ALL_IF
  170. bzero(&if_inaddr.un, sizeof(if_inaddr.un));
  171. #else
  172. // Read interface adapter link-local address and use it
  173. // to bind the multicast IF to this socket.
  174. //
  175. // (Note the interface may have other non-LL IPV6 addresses as well,
  176. // but it doesn't matter in this context as the address is only
  177. // used to identify the interface.)
  178. err = esp_netif_get_ip6_linklocal(EXAMPLE_INTERFACE, (esp_ip6_addr_t*)&if_ipaddr);
  179. inet6_addr_from_ip6addr(&if_inaddr, &if_ipaddr);
  180. if (err != ESP_OK) {
  181. ESP_LOGE(V6TAG, "Failed to get IPV6 LL address. Error 0x%x", err);
  182. goto err;
  183. }
  184. #endif // LISTEN_ALL_IF
  185. // search for netif index
  186. netif_index = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE);
  187. if(netif_index < 0) {
  188. ESP_LOGE(V6TAG, "Failed to get netif index");
  189. goto err;
  190. }
  191. // Assign the multicast source interface, via its IP
  192. err = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, &netif_index,sizeof(uint8_t));
  193. if (err < 0) {
  194. ESP_LOGE(V6TAG, "Failed to set IPV6_MULTICAST_IF. Error %d", errno);
  195. goto err;
  196. }
  197. // Assign multicast TTL (set separately from normal interface TTL)
  198. uint8_t ttl = MULTICAST_TTL;
  199. setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(uint8_t));
  200. if (err < 0) {
  201. ESP_LOGE(V6TAG, "Failed to set IPV6_MULTICAST_HOPS. Error %d", errno);
  202. goto err;
  203. }
  204. #if MULTICAST_LOOPBACK
  205. // select whether multicast traffic should be received by this device, too
  206. // (if setsockopt() is not called, the default is no)
  207. uint8_t loopback_val = MULTICAST_LOOPBACK;
  208. err = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
  209. &loopback_val, sizeof(uint8_t));
  210. if (err < 0) {
  211. ESP_LOGE(V6TAG, "Failed to set IPV6_MULTICAST_LOOP. Error %d", errno);
  212. goto err;
  213. }
  214. #endif
  215. // this is also a listening socket, so add it to the multicast
  216. // group for listening...
  217. #ifdef CONFIG_EXAMPLE_IPV6
  218. // Configure multicast address to listen to
  219. err = inet6_aton(MULTICAST_IPV6_ADDR, &v6imreq.ipv6mr_multiaddr);
  220. if (err != 1) {
  221. ESP_LOGE(V6TAG, "Configured IPV6 multicast address '%s' is invalid.", MULTICAST_IPV6_ADDR);
  222. goto err;
  223. }
  224. ESP_LOGI(TAG, "Configured IPV6 Multicast address %s", inet6_ntoa(v6imreq.ipv6mr_multiaddr));
  225. ip6_addr_t multi_addr;
  226. inet6_addr_to_ip6addr(&multi_addr, &v6imreq.ipv6mr_multiaddr);
  227. if (!ip6_addr_ismulticast(&multi_addr)) {
  228. ESP_LOGW(V6TAG, "Configured IPV6 multicast address '%s' is not a valid multicast address. This will probably not work.", MULTICAST_IPV6_ADDR);
  229. }
  230. // Configure source interface
  231. v6imreq.ipv6mr_interface = (unsigned int)netif_index;
  232. err = setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
  233. &v6imreq, sizeof(struct ipv6_mreq));
  234. if (err < 0) {
  235. ESP_LOGE(V6TAG, "Failed to set IPV6_ADD_MEMBERSHIP. Error %d", errno);
  236. goto err;
  237. }
  238. #endif
  239. #if CONFIG_EXAMPLE_IPV4_V6
  240. // Add the common IPV4 config options
  241. err = socket_add_ipv4_multicast_group(sock, false);
  242. if (err < 0) {
  243. goto err;
  244. }
  245. #endif
  246. #if CONFIG_EXAMPLE_IPV4_V6
  247. int only = 0;
  248. #else
  249. int only = 1; /* IPV6-only socket */
  250. #endif
  251. err = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &only, sizeof(int));
  252. if (err < 0) {
  253. ESP_LOGE(V6TAG, "Failed to set IPV6_V6ONLY. Error %d", errno);
  254. goto err;
  255. }
  256. ESP_LOGI(TAG, "Socket set IPV6-only");
  257. // All set, socket is configured for sending and receiving
  258. return sock;
  259. err:
  260. close(sock);
  261. return -1;
  262. }
  263. #endif
  264. static void mcast_example_task(void *pvParameters)
  265. {
  266. while (1) {
  267. int sock;
  268. #ifdef CONFIG_EXAMPLE_IPV4_ONLY
  269. sock = create_multicast_ipv4_socket();
  270. if (sock < 0) {
  271. ESP_LOGE(TAG, "Failed to create IPv4 multicast socket");
  272. }
  273. #else
  274. sock = create_multicast_ipv6_socket();
  275. if (sock < 0) {
  276. ESP_LOGE(TAG, "Failed to create IPv6 multicast socket");
  277. }
  278. #endif
  279. if (sock < 0) {
  280. // Nothing to do!
  281. vTaskDelay(5 / portTICK_PERIOD_MS);
  282. continue;
  283. }
  284. #ifdef CONFIG_EXAMPLE_IPV4
  285. // set destination multicast addresses for sending from these sockets
  286. struct sockaddr_in sdestv4 = {
  287. .sin_family = PF_INET,
  288. .sin_port = htons(UDP_PORT),
  289. };
  290. // We know this inet_aton will pass because we did it above already
  291. inet_aton(MULTICAST_IPV4_ADDR, &sdestv4.sin_addr.s_addr);
  292. #endif
  293. #ifdef CONFIG_EXAMPLE_IPV6
  294. struct sockaddr_in6 sdestv6 = {
  295. .sin6_family = PF_INET6,
  296. .sin6_port = htons(UDP_PORT),
  297. };
  298. // We know this inet_aton will pass because we did it above already
  299. inet6_aton(MULTICAST_IPV6_ADDR, &sdestv6.sin6_addr);
  300. #endif
  301. // Loop waiting for UDP received, and sending UDP packets if we don't
  302. // see any.
  303. int err = 1;
  304. while (err > 0) {
  305. struct timeval tv = {
  306. .tv_sec = 2,
  307. .tv_usec = 0,
  308. };
  309. fd_set rfds;
  310. FD_ZERO(&rfds);
  311. FD_SET(sock, &rfds);
  312. int s = select(sock + 1, &rfds, NULL, NULL, &tv);
  313. if (s < 0) {
  314. ESP_LOGE(TAG, "Select failed: errno %d", errno);
  315. err = -1;
  316. break;
  317. }
  318. else if (s > 0) {
  319. if (FD_ISSET(sock, &rfds)) {
  320. // Incoming datagram received
  321. char recvbuf[48];
  322. char raddr_name[32] = { 0 };
  323. struct sockaddr_storage raddr; // Large enough for both IPv4 or IPv6
  324. socklen_t socklen = sizeof(raddr);
  325. int len = recvfrom(sock, recvbuf, sizeof(recvbuf)-1, 0,
  326. (struct sockaddr *)&raddr, &socklen);
  327. if (len < 0) {
  328. ESP_LOGE(TAG, "multicast recvfrom failed: errno %d", errno);
  329. err = -1;
  330. break;
  331. }
  332. // Get the sender's address as a string
  333. #ifdef CONFIG_EXAMPLE_IPV4
  334. if (raddr.ss_family == PF_INET) {
  335. inet_ntoa_r(((struct sockaddr_in *)&raddr)->sin_addr,
  336. raddr_name, sizeof(raddr_name)-1);
  337. }
  338. #endif
  339. #ifdef CONFIG_EXAMPLE_IPV6
  340. if (raddr.ss_family== PF_INET6) {
  341. inet6_ntoa_r(((struct sockaddr_in6 *)&raddr)->sin6_addr, raddr_name, sizeof(raddr_name)-1);
  342. }
  343. #endif
  344. ESP_LOGI(TAG, "received %d bytes from %s:", len, raddr_name);
  345. recvbuf[len] = 0; // Null-terminate whatever we received and treat like a string...
  346. ESP_LOGI(TAG, "%s", recvbuf);
  347. }
  348. }
  349. else { // s == 0
  350. // Timeout passed with no incoming data, so send something!
  351. static int send_count;
  352. const char sendfmt[] = "Multicast #%d sent by ESP32\n";
  353. char sendbuf[48];
  354. char addrbuf[32] = { 0 };
  355. int len = snprintf(sendbuf, sizeof(sendbuf), sendfmt, send_count++);
  356. if (len > sizeof(sendbuf)) {
  357. ESP_LOGE(TAG, "Overflowed multicast sendfmt buffer!!");
  358. send_count = 0;
  359. err = -1;
  360. break;
  361. }
  362. struct addrinfo hints = {
  363. .ai_flags = AI_PASSIVE,
  364. .ai_socktype = SOCK_DGRAM,
  365. };
  366. struct addrinfo *res;
  367. #ifdef CONFIG_EXAMPLE_IPV4 // Send an IPv4 multicast packet
  368. #ifdef CONFIG_EXAMPLE_IPV4_ONLY
  369. hints.ai_family = AF_INET; // For an IPv4 socket
  370. #else
  371. #ifdef CONFIG_ESP_NETIF_TCPIP_LWIP // Resolving IPv4 mapped IPv6 addresses is supported only in the official TCPIP_LWIP stack (esp-lwip)
  372. hints.ai_family = AF_INET6; // For an IPv4 socket with V4 mapped addresses
  373. hints.ai_flags |= AI_V4MAPPED;
  374. #endif // CONFIG_ESP_NETIF_TCPIP_LWIP
  375. #endif
  376. int err = getaddrinfo(CONFIG_EXAMPLE_MULTICAST_IPV4_ADDR,
  377. NULL,
  378. &hints,
  379. &res);
  380. if (err < 0) {
  381. ESP_LOGE(TAG, "getaddrinfo() failed for IPV4 destination address. error: %d", err);
  382. break;
  383. }
  384. if (res == 0) {
  385. ESP_LOGE(TAG, "getaddrinfo() did not return any addresses");
  386. break;
  387. }
  388. #ifdef CONFIG_EXAMPLE_IPV4_ONLY
  389. ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(UDP_PORT);
  390. inet_ntoa_r(((struct sockaddr_in *)res->ai_addr)->sin_addr, addrbuf, sizeof(addrbuf)-1);
  391. ESP_LOGI(TAG, "Sending to IPV4 multicast address %s:%d...", addrbuf, UDP_PORT);
  392. #else
  393. ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = htons(UDP_PORT);
  394. inet6_ntoa_r(((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, addrbuf, sizeof(addrbuf)-1);
  395. ESP_LOGI(TAG, "Sending to IPV6 (V4 mapped) multicast address %s port %d (%s)...", addrbuf, UDP_PORT, CONFIG_EXAMPLE_MULTICAST_IPV4_ADDR);
  396. #endif
  397. err = sendto(sock, sendbuf, len, 0, res->ai_addr, res->ai_addrlen);
  398. freeaddrinfo(res);
  399. if (err < 0) {
  400. ESP_LOGE(TAG, "IPV4 sendto failed. errno: %d", errno);
  401. break;
  402. }
  403. #endif
  404. #ifdef CONFIG_EXAMPLE_IPV6
  405. hints.ai_family = AF_INET6;
  406. hints.ai_protocol = 0;
  407. err = getaddrinfo(CONFIG_EXAMPLE_MULTICAST_IPV6_ADDR,
  408. NULL,
  409. &hints,
  410. &res);
  411. if (err < 0) {
  412. ESP_LOGE(TAG, "getaddrinfo() failed for IPV6 destination address. error: %d", err);
  413. break;
  414. }
  415. struct sockaddr_in6 *s6addr = (struct sockaddr_in6 *)res->ai_addr;
  416. s6addr->sin6_port = htons(UDP_PORT);
  417. inet6_ntoa_r(s6addr->sin6_addr, addrbuf, sizeof(addrbuf)-1);
  418. ESP_LOGI(TAG, "Sending to IPV6 multicast address %s port %d...", addrbuf, UDP_PORT);
  419. err = sendto(sock, sendbuf, len, 0, res->ai_addr, res->ai_addrlen);
  420. freeaddrinfo(res);
  421. if (err < 0) {
  422. ESP_LOGE(TAG, "IPV6 sendto failed. errno: %d", errno);
  423. break;
  424. }
  425. #endif
  426. }
  427. }
  428. ESP_LOGE(TAG, "Shutting down socket and restarting...");
  429. shutdown(sock, 0);
  430. close(sock);
  431. }
  432. }
  433. void app_main(void)
  434. {
  435. ESP_ERROR_CHECK(nvs_flash_init());
  436. ESP_ERROR_CHECK(esp_netif_init());
  437. ESP_ERROR_CHECK(esp_event_loop_create_default());
  438. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  439. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  440. * examples/protocols/README.md for more information about this function.
  441. */
  442. ESP_ERROR_CHECK(example_connect());
  443. xTaskCreate(&mcast_example_task, "mcast_task", 4096, NULL, 5, NULL);
  444. }