Chinaunix首页 | 论坛 | 博客
  • 博客访问: 41132
  • 博文数量: 18
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2015-05-19 15:23
个人简介

转身撞上猪

文章分类

全部博文(18)

文章存档

2017年(18)

我的朋友

分类: C/C++

2017-03-11 18:46:55

gethostbyname 和 gethostbyaddr 函数声明如下:
#include
struct hostent *gethostbyname(const char *nmae);
//返回:成功则为非NULL指针,若出错则为NULL指针,同时设置h_errno.
struct hostent *gethostbyaddr(const char *addr, int len, 0);
//返回:成功则为非NULL指针,若出错则为NULL指针,同时设置h_errno.

结构体hostent


点击(此处)折叠或打开

  1. /* DNS host entry structure */
  2.  struct hostent {
  3.      char *h_hname;
  4.      char **h_aliases;
  5.      int h_addrtype;
  6.      int h_length;
  7.      char **h_addr_list;
  8.  }


示例代码如下:


点击(此处)折叠或打开

  1. #include
  2.  #include
  3.  #include
  4.  #include
  5.  #include

  6.  int main(int argc, char * argv[])
  7.  {
  8.      char **pp;
  9.     struct in_addr addr;
  10.      struct hostent *hostp;

  11.      if(argc != 2) {
  12.          fprintf(stderr, "usage: %s \n", argv[0]);
  13.          exit(0);
  14.      }

  15.      if(inet_aton(argv[1], &addr))
  16.          hostp = gethostbyaddr((const char *)&addr, sizeof(addr), AF_INET);
  17.      else
  18.          hostp = gethostbyname(argv[1]);

  19.      printf("official hostname: %s\n", hostp->h_name);

  20.      for(pp = hostp->h_aliases; *pp != NULL; pp++) {
  21.          printf("alias: %s\n", *pp);
  22.      }

  23.      for(pp = hostp->h_addr_list; *pp != NULL; pp++) {
  24.          //addr.s_addr = ((struct in_addr *)*pp)->s_addr;
  25.          addr.s_addr = *(unsigned int *)*pp;
  26.          printf("address: %s\n", inet_ntoa(addr));
  27.      }


  28.  }

 
编译
执行结果如下:
[root@CTOServer001 testprogram]# gcc -g exam002.c -o exam002
[root@CTOServer001 testprogram]# ./exam002 
official hostname:
alias:
address: 119.75.217.109
address: 119.75.218.70
[root@CTOServer001 testprogram]# ./exam002  127.0.0.1
official hostname: localhost
alias: localhost.localdomain
alias: localhost4
alias: localhost4.localdomain4
address: 127.0.0.1
[root@CTOServer001 testprogram]#

阅读(1396) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:tcp状态转换图

给主人留下些什么吧!~~