织梦CMS - 轻松建站从此开始!

罗索

DNS解析 ---gethostbyname函数

落鹤生 发布于 2012-02-15 16:35 点击:次 
如果你不知道 DNS 的意思,那么我告诉你,他代表"域名服务 (Domain Name Service)"。 他主要的功能是:你给他一个容易记忆的某站点的地址,他给你 IP 地址(然后你就可以 使用 bind(), connect(), sendto() 或者其他函数。)
TAG:

DNS--You say "whitehouse.gov", I say "198.137.240.100"
如果你不知道 DNS 的意思,那么我告诉你,他代表"域名服务 (Domain Name Service)"。 他主要的功能是:你给他一个容易记忆的某站点的地址,他给你 IP 地址(然后你就可以 使用 bind(), connect(), sendto() 或者其他函数。)当一个人 输入:
    $ telnet whitehouse.gov
telnet 能知道他将连接 (connect()) 到 "198.137.240.100"。

但是这是如何工作的呢? 你可以调用函数 gethostbyname():

  1. #include <netdb.h> 
  2. struct hostent *gethostbyname(const char *name); 

很明白的是,他返回一个指向 struct hostent 的指针。这个数据结构是 这样的:

  1. struct hostent { 
  2.     char    *h_name; 
  3.     char    **h_aliases; 
  4.     int     h_addrtype; 
  5.     int     h_length; 
  6.     char    **h_addr_list; 
  7. }; 
  8. #define h_addr h_addr_list[0] 

这里是这个数据结构的详细资料: struct hostent:
h_name - Official name of the host.
h_aliases - A NULL-terminated array of alternate names for the host.
h_addrtype - The type of address being returned; usually AF_INET.
h_length - The length of the address in bytes.
h_addr_list - A zero-terminated array of network addresses for the host. Host addresses are in Network Byte Order.
h_addr - The first address in h_addr_list.

gethostbyname() 成功时返回一个指向 struct hostent 的 指针,或者是个空 (NULL) 指针。(但是和以前不同,errno 不设置,h_errno 设置错误信息。请看下面的 herror()。)

但是如何使用呢? 这个函数可不象他看上去那么难用。

这里是个例子:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <errno.h> 
  4. #include <netdb.h> 
  5. #include <sys/types.h> 
  6. #include <netinet/in.h> 
  7.  
  8. int main(int argc, char *argv[]) 
  9. struct hostent *h; 
  10.  
  11. if (argc != 2) { /* error check the command line */ 
  12. fprintf(stderr,"usage: getip address\n"); 
  13. exit(1); 
  14.  
  15. if ((h=gethostbyname(argv[1])) == NULL) { /* get the host info */ 
  16. herror("gethostbyname"); 
  17. exit(1); 
  18.  
  19. printf("Host name : %s\n", h->h_name); 
  20. printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr))); 
  21.  
  22. return 0; 

在使用 gethostbyname() 的时候,你不能用 perror() 打印错误信息(因 为 errno 没有使用),你应该调用 herror()。

相当简单,你只是传递一个保存机器名的自负串(例如 "whitehouse.gov") 给 gethostbyname(),然后从返回的数据结构 struct hostent 中 收集信息。

唯一让人迷惑的是打印 IP 地址信息。h->h_addr 是一个 char *, 但是 inet_ntoa() 需要的是 struct in_addr。因此,我 转换 h->h_addr 成 struct in_addr *,然后得到数据。

(haiyan0106)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201202/15715.html]
本文出处:CSDN博客 作者:haiyan0106 原文
顶一下
(4)
80%
踩一下
(1)
20%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容