vc中将IP转换为域名

2013-09-26 19:37:09 · 作者: · 浏览: 84

  这可以用gethostbyaddr( )来完成.

  和gethostbyname( )一样,它也返回一个struct hostent类型的指针.

  在多线程环境下也有个替代函数gethostbyaddr_r( ).下划线后的r代表reentrant,

  意味着可以安全地重入.

  #include

  #include

  #include

  #include

  main(int argc, const char **argv)

  {

  u_long addr;

  struct hostent *hp;

  char **p;

  if (argc != 2) {

  printf("用法: %s IP地址 ", argv[0]);

  exit (1);

  }

  if ((int)(addr = inet_addr(argv )) == -1) {

  printf("错误的IP地址. ");

  exit (2);

  }

  hp = gethostbyaddr((char *)&addr, sizeof (addr), AF_INET);

  if (hp == NULL) {

  printf("Host information about %s not found. ", argv );

  exit (3);

  }

  printf("Official name: %s ",hp->h_name); //正式域名

  printf("IP Addr: ");

  for (p = hp->h_addr_list; *p ; p++) //循环显示所有IP

  printf(" %s ", inet_ntoa(*p));

  printf("Aliases: ");

  for (p = hp->h_aliases; *p ; p++) //循环显示所有别名

  printf(" %s ", *p);

  }