Chinaunix首页 | 论坛 | 博客
  • 博客访问: 240896
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: LINUX

2013-01-09 15:35:59

1、程序要求:判断字符串,是否为ip地址或主机名称,并打印相关信息。
2、程序代码:

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <netdb.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <sys/types.h>
  10. #include <arpa/inet.h>

  11. int main(int argc ,char **argv)
  12. {
  13.         struct sockaddr_in addr;
  14.         struct hostent *host;
  15.         char **alias;
  16.         
  17.         if(argc<2)
  18.         {
  19.          fprintf(stderr,"Usage:%s hostname|ip..\n\a",argv[0]);
  20.          exit(1);
  21.         }
  22.         
  23.         argv++;
  24.         for(;*argv!=NULL;argv++)
  25.         { printf("1");
  26.                 /* 这里我们假设是IP*/
  27.                 if(inet_aton(*argv,&addr.sin_addr)!=0)
  28.                 {
  29.                    host=gethostbyaddr((char *)&addr.sin_addr,4,AF_INET);
  30.                    printf("Address information of Ip %s\n",*argv);
  31.                 }
  32.                 else
  33.                 {
  34.                       /* 失败,难道是域名?*/
  35.                       host=gethostbyname(*argv);
  36.                       printf("Address information of host %s\n",*argv);
  37.                 }
  38.                 if(host==NULL)
  39.                 {
  40.                         /* 都不是 ,算了不找了*/
  41.                         fprintf(stderr,"No address information of %s\n",*argv);
  42.                         continue;
  43.                 }
  44.                 printf("Official host name %s\n",host->h_name);
  45.                 printf("Name aliases:");
  46.                 for(alias=host->h_aliases;*alias!=NULL;alias++)
  47.                  printf("%s ,",*alias);
  48.                 printf("\nIp address:");
  49.                 for(alias=host->h_addr_list;*alias!=NULL;alias++)
  50.                   printf("%s ,",inet_ntoa(*(struct in_addr *)(*alias)));
  51.         }
  52. }

阅读(4135) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~