1. 使用gethostbyname(char*)函数,拿到struct hostent
2. 使用inet_ntop()转换成ip地址
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> int main(int argc, char **argv) { char *hostname="www.baidu.com"; struct hostent *hptr; if ((hptr = gethostbyname(hostname)) == NULL) { printf("gethotbyname error "); return 1; } printf("offecial hostname:%s ", hptr->h_name); char **aliasPtrList = hptr->h_aliases; for (; *aliasPtrList != NULL; aliasPtrList++) printf("alias:%s ", *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 ", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent))); } printf("first address:%s ", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent))); break; default: printf("unkown address type "); } return 0; }