前一帖子,实验了如何使用adns库实现解析,用起来还是麻烦,直接使用系统函数,更直接:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <resolv.h> // 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<struct in_addr*>(phost->h_addr);
printf("official hostname: %s\n", phost->h_name);
for (pptr = phost->h_aliases; *pptr != NULL; pptr++)
{
printf("\talias: %s\n", *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: %s\n", inet_ntop(phost->h_addrtype, *pptr, ip, sizeof(ip)));
}
break;
default:
printf("unknow address type.");
break;
}
}
else
{
printf("ret =%d, err=%d\n", 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;
}
|