1. 程式人生 > >域名轉化到IP地址的實現

域名轉化到IP地址的實現

http://blog.csdn.net/u011239443/article/details/51655354

在linux中,有一些函式可以實現主機名和地址的轉化,最常見的有gethostbyname()、gethostbyaddr()等,它們都可以實現IPv4和IPv6的地址和主機名之間的轉化。其中gethostbyname()是將主機名轉化為IP地址,gethostbyaddr()則是逆操作,是將IP地址轉化為主機名。

    函式原型:

1    #include <netdb.h>
2 
3         struct hostent* gethostbyname(const char
* hostname); 4 5 struct hostent* gethostbyaddr(const char* addr, size_t len, int family);

    結構體:

 1 struct hostent
 2 
 3         {
 4 
 5             char *h_name;       /*正式主機名*/
 6 
 7             char **h_aliases;   /*主機別名*/
 8 
 9             int h_addrtype;     /*主機IP地址型別 IPv4為AF_INET
*/ 10 11 int h_length; /*主機IP地址位元組長度,對於IPv4是4位元組,即32位*/ 12 13 char **h_addr_list; /*主機的IP地址列表*/ 14 15 } 16 17 #define h_addr h_addr_list[0] /*儲存的是ip地址*/

      函式gethostbyname():用於將域名(www.baidu.com)或主機名轉換為IP地址。引數hostname指向存放域名或主機名的字串。

      函式gethostbyaddr():用於將IP地址轉換為域名或主機名。引數addr是一個IP地址,此時這個ip地址不是普通的字串,而是要通過函式inet_aton()轉換。len為IP地址的長度,AF_INET為4。family可用AF_INET:Ipv4或AF_INET6:Ipv6。

  Example:將百度的www.baidu.com 轉換為ip地址

 1 #include <netdb.h>
 2 
 3 #include <sys/socket.h>
 4 
 5 #include <stdio.h>
 6 
 7 int main(int argc, char **argv)
 8 
 9 {
10 
11 char *ptr, **pptr;
12 
13     struct hostent *hptr;
14 
15     char str[32] = {'\0'};
16 
17 /* 取得命令後第一個引數,即要解析的域名或主機名 */
18 
19 ptr = argv[1];  //如www.baidu.com
20 
21 /* 呼叫gethostbyname()。結果存在hptr結構中 */
22 
23     if((hptr = gethostbyname(ptr)) == NULL)
24 
25     {
26 
27         printf(" gethostbyname error for host:%s\n", ptr);
28 
29         return 0;
30 
31     }
32 
33 /* 將主機的規範名打出來 */
34 
35     printf("official hostname:%s\n",hptr->h_name);
36 
37 /* 主機可能有多個別名,將所有別名分別打出來 */
38 
39 for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
40 
41 printf(" alias:%s\n",*pptr);
42 
43               /* 根據地址型別,將地址打出來 */
44 
45 switch(hptr->h_addrtype)
46 
47     {
48 
49 case AF_INET,AF_INET6:
50 
51 pptr=hptr->h_addr_list;
52 
53                             /* 將剛才得到的所有地址都打出來。其中呼叫了inet_ntop()函式 */
54 
55             for(; *pptr!=NULL; pptr++)
56 
57                 printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
58 
59             printf(" first address: %s\n", inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
60 
61         break;
62 
63         default:
64 
65             printf("unknown address type\n");
66 
67         break;
68 
69     }
70 
71     return 0;
72 
73 }

編譯執行

#gcc test.c

#./a.out www.baidu.com

official hostname:www.a.shifen.com

alias:www.baidu.com

address: 220.181.111.148

……

first address: 220.181.111.148