码迷,mamicode.com
首页 > Web开发 > 详细

【learning log】Linux network programming

时间:2014-08-19 14:11:15      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

DNS host entry 包含 DNS database 中有关某一 domin name 或 ip address 的 DNS 信息。

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 };

hostinfo 程序, 用来从 ip 或 domin name 解析 DNS info。

bubuko.com,布布扣
 1 /*This program is modified from CSAPP: hostinfo.c
 2  */
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <unistd.h>
 6 #include <string.h>
 7 #include <ctype.h>
 8 #include <setjmp.h>
 9 #include <signal.h>
10 #include <sys/time.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <sys/mman.h>
16 #include <errno.h>
17 #include <math.h>
18 #include <pthread.h>
19 #include <semaphore.h>
20 #include <sys/socket.h>
21 #include <netdb.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
24 #include <netinet/in.h>
25 #include <netdb.h>
26 
27 void dns_error(char * msg)
28 {
29   fprintf(stderr, "%s: DNS error %d\n", msg, h_errno);
30 }
31 
32 struct hostent *Gethostbyaddr(const char * addr, int len, int flag)
33 {
34   struct hostent *p;
35   if ((p = gethostbyaddr(addr, len, flag)) == NULL)
36     dns_error("Gethostbyaddr error");
37   return p;
38 }
39 
40 struct hostent *Gethostbyname(const char * name)
41 {
42   struct hostent *p;
43   if ((p = gethostbyname(name)) == NULL)
44     dns_error("Gethostbyname error");
45   return p;
46 }
47 
48  int main(int argc, char ** argv)
49 {
50   char **pp;
51   struct in_addr addr;
52   struct hostent *hostp;
53 
54   if (argc != 2) {
55     fprintf(stderr, "usage: %s <domain name or dotted-decimal>\n",
56     argv[0]);
57     exit(0);
58     }
59   int af_inet = AF_INET;
60   if (inet_aton(argv[1], &addr) != 0)
61     hostp = Gethostbyaddr((const char *)&addr, sizeof(addr), AF_INET);
62   else
63     hostp = Gethostbyname(argv[1]);
64 
65   if (hostp == NULL)
66     exit(0);
67 
68   printf("official hostname: %s\n", hostp->h_name);
69 
70   for (pp = hostp->h_aliases;*pp != NULL;pp++)
71     printf("alias: %s\n", *pp);
72 
73   for (pp = hostp->h_addr_list;*pp != NULL; pp++) {
74      addr.s_addr = ((struct in_addr *)*pp)->s_addr;
75     printf("address: %s\n", inet_ntoa(addr));     
76   }
77   exit(0);
78 }
hostinfo

 

【learning log】Linux network programming,布布扣,bubuko.com

【learning log】Linux network programming

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/slowlight/p/3921814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!