前一帖子,实验了如何使用adns库实现解析,用起来还是麻烦,直接使用系统函数,更直接:
#include#include #include #include #include #include #include #include #include #include #include #include // dns ///static thread_local char t_resolveBuffer[64 * 1024]; void test(const char *url) { char ip[INET_ADDRSTRLEN]; char *ptr, **pptr; struct hostent hostinfo; struct hostent *phost = NULL; int hostrrno = 0; memset(&hostinfo, 0, sizeof(hostinfo)); //该函数成功返回0,失败返回一个非0的数。 int ret = gethostbyname_r(url, &hostinfo, t_resolveBuffer, sizeof(t_resolveBuffer), &phost, &hostrrno); if (ret == 0 && phost != NULL) { // assert(phost->h_addrtype == AF_INET && phost->h_length == sizeof(uint32_t)); // out->addr_.sin_addr = *reinterpret_cast (phost->h_addr); printf("official hostname: %sn", phost->h_name); for (pptr = phost->h_aliases; *pptr != NULL; pptr++) { printf("talias: %sn", *pptr); } switch (phost->h_addrtype) { case AF_INET: pptr = phost->h_addr_list; for (; *pptr != NULL; pptr++) { // inet_ntoa只适用于ipv4地址,而inet_ntop适用ipv4和ipv6地址 printf("taddress: %sn", inet_ntop(phost->h_addrtype, *pptr, ip, sizeof(ip))); } break; default: printf("unknow address type."); break; } } else { printf("ret =%d, err=%dn", ret, hostrrno); return; } } int main() { char host[128]; res_init(); while (1) { scanf("%s", host); if (strlen(host) == 4 && 0 == strcmp(host, "exit")) break; test(host); } return 0; }



