版权声明:本文为博主原创文章,可以随意引用或转载,但未经博主允许不得用于任何商业用途。 https://blog.csdn.net/ustccw/article/details/84786289
RTOS v2.x 以及之前版本
#define EXAMPLE_DNS "a3.tuyaus.com"
static void dns_task(void* pvParameters)
{
printf("Waiting for WiFi access point ...");
while(!got_ip_flag) {
vTaskDelay(2000 / portTICK_RATE_MS);
}
int ret = 0, retry = 0;
char *target_name = "www.baidu.com";
struct hostent *hp = NULL;
do {
hp = gethostbyname(target_name);
} while (hp == NULL && retry++ < 20);
if(hp) {
// DNS OK
printf("DNS lookup succeeded. %s: %s\r\n", target_name, inet_ntoa(*(struct in_addr*)hp->h_addr));
} else {
// DNS failed
printf("DNS failed!\r\n");
}
hp = NULL; retry = 0;
do {
hp = gethostbyname(EXAMPLE_DNS);
} while (hp == NULL && retry++ < 20);
if(hp) {
// DNS OK
printf("DNS lookup succeeded. %s: %s\r\n", EXAMPLE_DNS, inet_ntoa(*(struct in_addr*)hp->h_addr));
} else {
// DNS failed
printf("DNS failed!\r\n");
}
vTaskDelete(NULL);
}
DNS 调试:
include/lwip/arch/cc.h
中打开宏#define LWIP_DEBUG
include/lwip/lwip/opt.h
中使能宏#define UDP_DEBUG LWIP_DBG_ON
- 重新编译
lwip
库 - 编译应用代码
RTOS v3.0 +
#define EXAMPLE_DNS CONFIG_DNS_DOMAIN_NAME // config by make menuconfig
static void dns_task(void* pvParameters)
{
ESP_LOGI(TAG, "Waiting for WiFi access point ...");
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
int ret = 0, retry = 0;
char *target_name = "www.baidu.com";
struct hostent *hp = NULL;
do {
hp = gethostbyname(target_name);
printf("retry1:%d\r\n", retry);
} while (hp == NULL && retry++ < 20);
if(hp) {
// DNS OK
ESP_LOGI(TAG, "DNS lookup succeeded. %s: %s", target_name, inet_ntoa(*(struct in_addr*)hp->h_addr));
} else {
// DNS failed
ESP_LOGE(TAG, "DNS failed!");
}
hp = NULL; retry = 0;
do {
hp = gethostbyname(EXAMPLE_DNS);
printf("retry2:%d\r\n", retry);
} while (hp == NULL && retry++ < 20);
if(hp) {
// DNS OK
ESP_LOGI(TAG, "DNS lookup succeeded. %s: %s", EXAMPLE_DNS, inet_ntoa(*(struct in_addr*)hp->h_addr));
} else {
// DNS failed
ESP_LOGE(TAG, "DNS failed!");
}
vTaskDelete(NULL);
}
DNS 调试:
调试 DNS 建议打开 make menuconfig
-> Component config
-> LWIP
-> Enable lwip Debug
-> Enable debugging for DNS
.