mdns_example_main.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /* MDNS-SD Query and advertise 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 "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. #include "esp_netif_ip_addr.h"
  11. #include "esp_system.h"
  12. #include "esp_event.h"
  13. #include "esp_log.h"
  14. #include "nvs_flash.h"
  15. #include "esp_netif.h"
  16. #include "protocol_examples_common.h"
  17. #include "mdns.h"
  18. #include "driver/gpio.h"
  19. #include "netdb.h"
  20. #define EXAMPLE_MDNS_INSTANCE CONFIG_MDNS_INSTANCE
  21. #define EXAMPLE_BUTTON_GPIO 0
  22. static const char * TAG = "mdns-test";
  23. static char * generate_hostname(void);
  24. #if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1
  25. static void query_mdns_host_with_gethostbyname(char * host);
  26. static void query_mdns_host_with_getaddrinfo(char * host);
  27. #endif
  28. static void initialise_mdns(void)
  29. {
  30. char * hostname = generate_hostname();
  31. //initialize mDNS
  32. ESP_ERROR_CHECK( mdns_init() );
  33. //set mDNS hostname (required if you want to advertise services)
  34. ESP_ERROR_CHECK( mdns_hostname_set(hostname) );
  35. ESP_LOGI(TAG, "mdns hostname set to: [%s]", hostname);
  36. //set default mDNS instance name
  37. ESP_ERROR_CHECK( mdns_instance_name_set(EXAMPLE_MDNS_INSTANCE) );
  38. //structure with TXT records
  39. mdns_txt_item_t serviceTxtData[3] = {
  40. {"board", "esp32"},
  41. {"u", "user"},
  42. {"p", "password"}
  43. };
  44. //initialize service
  45. ESP_ERROR_CHECK( mdns_service_add("ESP32-WebServer", "_http", "_tcp", 80, serviceTxtData, 3) );
  46. #if CONFIG_MDNS_MULTIPLE_INSTANCE
  47. ESP_ERROR_CHECK( mdns_service_add("ESP32-WebServer1", "_http", "_tcp", 80, NULL, 0) );
  48. #endif
  49. #if CONFIG_MDNS_PUBLISH_DELEGATE_HOST
  50. char *delegated_hostname;
  51. if (-1 == asprintf(&delegated_hostname, "%s-delegated", hostname)) {
  52. abort();
  53. }
  54. mdns_ip_addr_t addr4, addr6;
  55. esp_netif_str_to_ip4("10.0.0.1", &addr4.addr.u_addr.ip4);
  56. addr4.addr.type = ESP_IPADDR_TYPE_V4;
  57. esp_netif_str_to_ip6("fd11:22::1", &addr6.addr.u_addr.ip6);
  58. addr6.addr.type = ESP_IPADDR_TYPE_V6;
  59. addr4.next = &addr6;
  60. addr6.next = NULL;
  61. ESP_ERROR_CHECK( mdns_delegate_hostname_add(delegated_hostname, &addr4) );
  62. ESP_ERROR_CHECK( mdns_service_add_for_host("test0", "_http", "_tcp", delegated_hostname, 1234, serviceTxtData, 3) );
  63. free(delegated_hostname);
  64. #endif // CONFIG_MDNS_PUBLISH_DELEGATE_HOST
  65. //add another TXT item
  66. ESP_ERROR_CHECK( mdns_service_txt_item_set("_http", "_tcp", "path", "/foobar") );
  67. //change TXT item value
  68. ESP_ERROR_CHECK( mdns_service_txt_item_set_with_explicit_value_len("_http", "_tcp", "u", "admin", strlen("admin")) );
  69. free(hostname);
  70. }
  71. /* these strings match tcpip_adapter_if_t enumeration */
  72. static const char * if_str[] = {"STA", "AP", "ETH", "MAX"};
  73. /* these strings match mdns_ip_protocol_t enumeration */
  74. static const char * ip_protocol_str[] = {"V4", "V6", "MAX"};
  75. static void mdns_print_results(mdns_result_t *results)
  76. {
  77. mdns_result_t *r = results;
  78. mdns_ip_addr_t *a = NULL;
  79. int i = 1, t;
  80. while (r) {
  81. printf("%d: Interface: %s, Type: %s, TTL: %u\n", i++, if_str[r->tcpip_if], ip_protocol_str[r->ip_protocol],
  82. r->ttl);
  83. if (r->instance_name) {
  84. printf(" PTR : %s.%s.%s\n", r->instance_name, r->service_type, r->proto);
  85. }
  86. if (r->hostname) {
  87. printf(" SRV : %s.local:%u\n", r->hostname, r->port);
  88. }
  89. if (r->txt_count) {
  90. printf(" TXT : [%zu] ", r->txt_count);
  91. for (t = 0; t < r->txt_count; t++) {
  92. printf("%s=%s(%d); ", r->txt[t].key, r->txt[t].value ? r->txt[t].value : "NULL", r->txt_value_len[t]);
  93. }
  94. printf("\n");
  95. }
  96. a = r->addr;
  97. while (a) {
  98. if (a->addr.type == ESP_IPADDR_TYPE_V6) {
  99. printf(" AAAA: " IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6));
  100. } else {
  101. printf(" A : " IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4)));
  102. }
  103. a = a->next;
  104. }
  105. r = r->next;
  106. }
  107. }
  108. static void query_mdns_service(const char * service_name, const char * proto)
  109. {
  110. ESP_LOGI(TAG, "Query PTR: %s.%s.local", service_name, proto);
  111. mdns_result_t * results = NULL;
  112. esp_err_t err = mdns_query_ptr(service_name, proto, 3000, 20, &results);
  113. if(err){
  114. ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err));
  115. return;
  116. }
  117. if(!results){
  118. ESP_LOGW(TAG, "No results found!");
  119. return;
  120. }
  121. mdns_print_results(results);
  122. mdns_query_results_free(results);
  123. }
  124. static bool check_and_print_result(mdns_search_once_t *search)
  125. {
  126. // Check if any result is available
  127. mdns_result_t * result = NULL;
  128. if (!mdns_query_async_get_results(search, 0, &result)) {
  129. return false;
  130. }
  131. if (!result) { // search timeout, but no result
  132. return true;
  133. }
  134. // If yes, print the result
  135. mdns_ip_addr_t * a = result->addr;
  136. while (a) {
  137. if(a->addr.type == ESP_IPADDR_TYPE_V6){
  138. printf(" AAAA: " IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6));
  139. } else {
  140. printf(" A : " IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4)));
  141. }
  142. a = a->next;
  143. }
  144. // and free the result
  145. mdns_query_results_free(result);
  146. return true;
  147. }
  148. static void query_mdns_hosts_async(const char * host_name)
  149. {
  150. ESP_LOGI(TAG, "Query both A and AAA: %s.local", host_name);
  151. mdns_search_once_t *s_a = mdns_query_async_new(host_name, NULL, NULL, MDNS_TYPE_A, 1000, 1, NULL);
  152. mdns_query_async_delete(s_a);
  153. mdns_search_once_t *s_aaaa = mdns_query_async_new(host_name, NULL, NULL, MDNS_TYPE_AAAA, 1000, 1, NULL);
  154. while (s_a || s_aaaa) {
  155. if (s_a && check_and_print_result(s_a)) {
  156. ESP_LOGI(TAG, "Query A %s.local finished", host_name);
  157. mdns_query_async_delete(s_a);
  158. s_a = NULL;
  159. }
  160. if (s_aaaa && check_and_print_result(s_aaaa)) {
  161. ESP_LOGI(TAG, "Query AAAA %s.local finished", host_name);
  162. mdns_query_async_delete(s_aaaa);
  163. s_aaaa = NULL;
  164. }
  165. }
  166. }
  167. static void query_mdns_host(const char * host_name)
  168. {
  169. ESP_LOGI(TAG, "Query A: %s.local", host_name);
  170. struct esp_ip4_addr addr;
  171. addr.addr = 0;
  172. esp_err_t err = mdns_query_a(host_name, 2000, &addr);
  173. if(err){
  174. if(err == ESP_ERR_NOT_FOUND){
  175. ESP_LOGW(TAG, "%s: Host was not found!", esp_err_to_name(err));
  176. return;
  177. }
  178. ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err));
  179. return;
  180. }
  181. ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr));
  182. }
  183. static void initialise_button(void)
  184. {
  185. gpio_config_t io_conf = {0};
  186. io_conf.intr_type = GPIO_INTR_DISABLE;
  187. io_conf.pin_bit_mask = BIT64(EXAMPLE_BUTTON_GPIO);
  188. io_conf.mode = GPIO_MODE_INPUT;
  189. io_conf.pull_up_en = 1;
  190. io_conf.pull_down_en = 0;
  191. gpio_config(&io_conf);
  192. }
  193. static void check_button(void)
  194. {
  195. static bool old_level = true;
  196. bool new_level = gpio_get_level(EXAMPLE_BUTTON_GPIO);
  197. if (!new_level && old_level) {
  198. query_mdns_hosts_async("esp32-mdns");
  199. query_mdns_host("esp32");
  200. query_mdns_service("_arduino", "_tcp");
  201. query_mdns_service("_http", "_tcp");
  202. query_mdns_service("_printer", "_tcp");
  203. query_mdns_service("_ipp", "_tcp");
  204. query_mdns_service("_afpovertcp", "_tcp");
  205. query_mdns_service("_smb", "_tcp");
  206. query_mdns_service("_ftp", "_tcp");
  207. query_mdns_service("_nfs", "_tcp");
  208. }
  209. old_level = new_level;
  210. }
  211. static void mdns_example_task(void *pvParameters)
  212. {
  213. #if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1
  214. /* Send initial queries that are started by CI tester */
  215. query_mdns_host("tinytester");
  216. query_mdns_host_with_gethostbyname("tinytester-lwip.local");
  217. query_mdns_host_with_getaddrinfo("tinytester-lwip.local");
  218. #endif
  219. while (1) {
  220. check_button();
  221. vTaskDelay(50 / portTICK_PERIOD_MS);
  222. }
  223. }
  224. void app_main(void)
  225. {
  226. ESP_ERROR_CHECK(nvs_flash_init());
  227. ESP_ERROR_CHECK(esp_netif_init());
  228. ESP_ERROR_CHECK(esp_event_loop_create_default());
  229. initialise_mdns();
  230. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  231. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  232. * examples/protocols/README.md for more information about this function.
  233. */
  234. ESP_ERROR_CHECK(example_connect());
  235. initialise_button();
  236. xTaskCreate(&mdns_example_task, "mdns_example_task", 2048, NULL, 5, NULL);
  237. }
  238. /** Generate host name based on sdkconfig, optionally adding a portion of MAC address to it.
  239. * @return host name string allocated from the heap
  240. */
  241. static char* generate_hostname(void)
  242. {
  243. #ifndef CONFIG_MDNS_ADD_MAC_TO_HOSTNAME
  244. return strdup(CONFIG_MDNS_HOSTNAME);
  245. #else
  246. uint8_t mac[6];
  247. char *hostname;
  248. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  249. if (-1 == asprintf(&hostname, "%s-%02X%02X%02X", CONFIG_MDNS_HOSTNAME, mac[3], mac[4], mac[5])) {
  250. abort();
  251. }
  252. return hostname;
  253. #endif
  254. }
  255. #if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1
  256. /**
  257. * @brief Executes gethostbyname and displays list of resolved addresses.
  258. * Note: This function is used only to test advertised mdns hostnames resolution
  259. */
  260. static void query_mdns_host_with_gethostbyname(char * host)
  261. {
  262. struct hostent *res = gethostbyname(host);
  263. if (res) {
  264. unsigned int i = 0;
  265. while (res->h_addr_list[i] != NULL) {
  266. ESP_LOGI(TAG, "gethostbyname: %s resolved to: %s", host, inet_ntoa(*(struct in_addr *) (res->h_addr_list[i])));
  267. i++;
  268. }
  269. }
  270. }
  271. /**
  272. * @brief Executes getaddrinfo and displays list of resolved addresses.
  273. * Note: This function is used only to test advertised mdns hostnames resolution
  274. */
  275. static void query_mdns_host_with_getaddrinfo(char * host)
  276. {
  277. struct addrinfo hints;
  278. struct addrinfo * res;
  279. memset(&hints, 0, sizeof(hints));
  280. hints.ai_family = AF_UNSPEC;
  281. hints.ai_socktype = SOCK_STREAM;
  282. if (!getaddrinfo(host, NULL, &hints, &res)) {
  283. while (res) {
  284. ESP_LOGI(TAG, "getaddrinfo: %s resolved to: %s", host,
  285. res->ai_family == AF_INET?
  286. inet_ntoa(((struct sockaddr_in *) res->ai_addr)->sin_addr):
  287. inet_ntoa(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr));
  288. res = res->ai_next;
  289. }
  290. }
  291. }
  292. #endif