mdns_example_main.c 10 KB

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