1. 使用gethostbyname(char*)函数,拿到struct hostent
2. 使用inet_ntop()转换成ip地址
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv) {
char *hostname="www.baidu.com";
struct hostent *hptr;
if ((hptr = gethostbyname(hostname)) == NULL) {
printf("gethotbyname error\n");
return 1;
}
printf("offecial hostname:%s\n", hptr->h_name);
char **aliasPtrList = hptr->h_aliases;
for (; *aliasPtrList != NULL; aliasPtrList++)
printf("alias:%s\n", *aliasPtrList);
char **addressList = hptr->h_addr_list;
char addressContent[32];
switch (hptr->h_addrtype) {
case AF_INET:
case AF_INET6:
for(; *addressList != NULL; addressList++) {
printf("address:%s\n", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent)));
}
printf("first address:%s\n", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent)));
break;
default:
printf("unkown address type\n");
}
return 0;
}