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。
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
时间: 2024-10-25 16:07:09