gethostbynameドメイン名に基づいてipアドレスを取得

10855 ワード

gethostbyname関数はドメイン名に基づいてサーバのipアドレスを解析し、構造体struct hostentを返します.
struct hostent構造体
#include 

struct hostent {
	char * h_name; 		/ *       * /
	char ** h_aliases; 	/ *     ,           * /
	int h_addrtype; 	/ *      :IPV4-AF_INET* /
	int h_length; 		/ *        ,  IPv4    , 32 * /
	char ** h_addr_list; / *    * /
}
#define h_addr h_addr_list [0] / *      * /

例:
//test_gethostbyname.c
#include 
#include 
#include 
#include 
#include 
#include 


int main(int argc, char **argv)
{
	char *hostname,**pptr;
	struct hostent *hptr;
	char str[32] = {0};


	hostname = argc < 2 ? "www.baidu.com" : argv[1];
	printf("hostname:%s
"
, hostname); if((hptr = gethostbyname(hostname)) == NULL) { printf("gethostbyname(%s) error(%s)
"
, hostname, strerror(errno)); return 0; } printf("official hostname:%s
"
, hptr->h_name); // for(pptr = hptr->h_aliases; *pptr != NULL; pptr++) // printf("alias: %s
"
, *pptr); switch(hptr->h_addrtype) // , { case AF_INET: case AF_INET6: pptr = hptr->h_addr_list; // printf("first address: %s
"
, inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str))); for(; *pptr != NULL; pptr++) // { //inet_ntop: printf("address: %s
"
, inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str))); } break; default: printf("unkown address type
"
); break; } return 0; }

参考資料https://blog.csdn.net/wynter_/article/details/52529685 https://kenby.iteye.com/blog/1149534 https://blog.csdn.net/test1280/article/details/82949596