c_cpp C中的基本DNS查找实用程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C中的基本DNS查找实用程序相关的知识,希望对你有一定的参考价值。

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char **argv) {
  struct addrinfo hints, *res, *ai;
  int error;
  char host[NI_MAXHOST];
  char hostname[NI_MAXHOST];

  char *name_to_search = NULL;

  if (argc > 1) {
    name_to_search = argv[1];
  }

  if (!name_to_search) {
	  fprintf(stderr, "Missing name to lookup!\n");
    exit(1);
  }

  /*
   * Request only one socket type from getaddrinfo(). Else we
   * would get both SOCK_DGRAM and SOCK_STREAM, and print two
   * copies of each numeric address.
   */
  memset(&hints, 0, sizeof hints);
  hints.ai_family = PF_UNSPEC;    /* IPv4, IPv6, or anything */
  hints.ai_socktype = SOCK_DGRAM; /* Dummy socket type */
  hints.ai_flags |= AI_CANONNAME; /* Want cannonical name */

  /*
   * Use getaddrinfo() to resolve "www.kame.net" and allocate
   * a linked list of addresses.
   */
  error = getaddrinfo(name_to_search, NULL, &hints, &ai);
  if (error) {
    fprintf(stderr, "%s\n", gai_strerror(error));
    exit(1);
  }

  /* Iterate the linked list. */
  for (res = ai; res; res = res->ai_next) {
    /*
     * Use getnameinfo() to convert res->ai_addr to a
     * printable string.
     *
     * NI_NUMERICHOST means to present the numeric address
     * without doing reverse DNS to get a domain name.
     */
    error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL,
                        0, NI_NUMERICHOST);
    if (error) {
      fprintf(stderr, "%s\n", gai_strerror(error));
      continue;
    }
    error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname,
                        sizeof hostname, NULL, 0, 0);
    if (error) {
      fprintf(stderr, "%s\n", gai_strerror(error));
      continue;
    }
    /* Print the numeric address(es). */
    if (strcmp(host, hostname) == 0) {
      printf("%-15s -> %s\n", host,
             res->ai_canonname != NULL ? res->ai_canonname : "no canonical");
    } else {
      printf("%-15s -> %s %s\n", host, hostname,
             res->ai_canonname != NULL ? res->ai_canonname : "no canonical");
    }
  }

  /* Free the linked list, as if it mattered here! :p. */
  freeaddrinfo(ai);

  return 0;
}

以上是关于c_cpp C中的基本DNS查找实用程序的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp EMMC终身测试实用程序

c_cpp 模具实用程序 - 终止带有错误消息和退出代码的C程序

c_cpp BrickstorOS的快速单文件网络统计实用程序

c_cpp 在给定pid的情况下计算打开文件描述符的实用程序

c_cpp 二维数组中的查找.C

c_cpp dns-block.c para spotify