原工程:
https://zh.arslanbar.net/post.php?t=24584首先,打开配置文件lwipopts.h,添加如下三行,开启DNS:
#define LWIP_DNS 1
#define LWIP_DHCP_PROVIDE_DNS_SERVERS 1 // 通过DHCP获取DNS服务器的地址
#define LWIP_RAND() ((u32_t)rand())
然后打开main.c,添加头文件:
#include "lwip/dns.h"
编写dns测试函数:
void dnsfound(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
{
printf("DNS Found IP: %s\n", ip4addr_ntoa(ipaddr));
}
void test_dns(struct netif *netif)
{
struct ip4_addr dnsip;
err_t err = dns_gethostbyname("zh.arslanbar.net", &dnsip, dnsfound, NULL);
if (err == ERR_OK)
printf("In cache! IP: %s\n", ip4addr_ntoa(&dnsip));
else
printf("Not in cache! err=%d\n", err);
}
在show_addr函数中调用test_dns函数:
void show_addr(struct netif *netif)
{
struct dhcp *dhcp = netif_dhcp_data(netif);
static uint8_t displayed = 0;
if (dhcp->state == DHCP_STATE_BOUND)
{
if (displayed == 0)
{
printf("DHCP分配成功!\n");
printf("IP地址: %s\n", ip4addr_ntoa(&dhcp->offered_ip_addr));
printf("子网掩码: %s\n", ip4addr_ntoa(&dhcp->offered_sn_mask));
printf("网关: %s\n", ip4addr_ntoa(&dhcp->offered_gw_addr));
printf("DNS服务器: %s\n", ip4addr_ntoa(dns_getserver(0))); // ★
displayed = 1;
test_dns(netif); // ★
}
}
else
displayed = 0;
}
最后,在main函数中的dhcp_start函数调用前加上:dns_init();