Chinaunix首页 | 论坛 | 博客
  • 博客访问: 335608
  • 博文数量: 56
  • 博客积分: 2058
  • 博客等级: 中尉
  • 技术积分: 688
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-11 09:19
个人简介

code rush

文章分类

全部博文(56)

文章存档

2012年(2)

2011年(54)

分类: LINUX

2011-06-15 11:32:37

写了一个批量查询域名dns查询小程序,读取文本中的域名,每行一个,输出对应IP

主要是用到了 struct hostent 结构
  1. struct hostent
  2. {
  3.     char *h_name;//主机正式名称
  4.     char **h_aliases;//别名列表
  5.     int h_addtype;//主机地址类型 v4orv6
  6.     int h_lenth;// 地址长度
  7.     char **h_addr_list;//IP 地址列表
  8. };
函数 gethostbyname() 可以根据主机名获取主机的信息,返回值就是指向struct hostent结构的一个指针。


  1. #include<unistd.h>
  2. #include<stdio.h>
  3. #include<netdb.h>


  4. int main(int argc,char *argv[])
  5. {
  6.     char host[128];
  7.     struct hostent *ht=NULL;
  8.     FILE *fp;
  9.     
  10.     if(argc<2)
  11.     {
  12.         printf("usage: dns_search file\n");
  13.         exit(1);
  14.     }
  15.     
  16.     printf("%s\n",argv[0]);
  17.     
  18.     fp=fopen(argv[1],"r");
  19.     
  20.     if(fp<0)
  21.     printf("open file error\n");
  22.     else
  23.     printf("open file sucess");
  24.     
  25.     while(fscanf(fp,"%s",host)!=EOF)
  26.     {
  27.         ht=gethostbyname(host);
  28.         
  29.         printf("%s\n",host);
  30.         
  31.         if(ht)
  32.         {
  33.             int i=0;
  34.             int j=0;
  35.             for(i=0;;i++)
  36.             {
  37.                 if(ht->h_addr_list[i] !=NULL)
  38.                 {
  39.                     j++;
  40.                 }
  41.                 else
  42.                 break;
  43.             }
  44.         
  45.             printf("%d\n",j);
  46.             for(i=0;i<=j;i++)
  47.             {
  48.                 if(ht->h_addr_list[i] !=NULL)
  49.                 {
  50.                     printf("%s\n",inet_ntoa((unsigned int*)ht->h_addr_list[i]));
  51.                 }
  52.                 else
  53.                 break;
  54.             }
  55.         
  56.         }
  57.         else
  58.         {
  59.             printf("0\n");
  60.         }
  61.     }
  62.     
  63. }
阅读(2248) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~