简体   繁体   English

如何获得与FQDN相关的IP列表

[英]how can I get the IPs list reffering to an FQDN

In my C++ linux application how can I get the IPs list reffering to an FQDN? 在我的C ++ Linux应用程序中,如何获得与FQDN相关的IP列表? (static IPs + dynamic IPs) (静态IP +动态IP)

10x 10倍

There is no principal difference between retrieving the mapping for a local and a fully qualified domain name. 检索本地和完全限定域名的映射之间没有主要区别。 Therefore, you can call the getaddrinfo as you would with any other domain name. 因此,您可以像使用其他任何域名一样调用getaddrinfo Note that there is no way to get the list of all IP addresses associated to a domain name because DNS servers are free to advertise only certain addresses or pick a few from a larger list. 请注意,由于DNS服务器可以自由地仅公布某些地址或从较大的列表中选择一些地址,因此无法获取与域名相关联的所有IP地址的列表。 For example, google.com will usually map to servers on your continent. 例如, google.com通常会映射到您所在大陆上的服务器。

Here's an example on how to use it: 这是有关如何使用它的示例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, char** argv) {
 const char* domain = argc>1 ? argv[1] : "example.com";
 struct addrinfo *result, *rp, hints;

 memset(&hints, 0, sizeof(hints));
 hints.ai_socktype = SOCK_STREAM; // TCP

 int tmp = getaddrinfo(domain, NULL, &hints, &result);
 if (tmp != 0) {
  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(tmp));
  return 1;
 }

 for (rp = result;rp != NULL;rp = rp->ai_next) {
  char buf[INET6_ADDRSTRLEN];
  switch (rp->ai_family) {
  case AF_INET:{
   struct in_addr* a4 = & ((struct sockaddr_in*) rp->ai_addr)->sin_addr;
   inet_ntop(rp->ai_family, a4, buf, sizeof(buf));
   printf("IPv4: %s\n", buf);
   break;}
  case AF_INET6:{
   struct in6_addr* a6 = & ((struct sockaddr_in6*) rp->ai_addr)->sin6_addr;
   inet_ntop(rp->ai_family, a6, buf, sizeof(buf));
   printf("IPv6: %s\n", buf);
   break;
  }}
 }

 freeaddrinfo(result);
 return 0;
}

This will output: 这将输出:

IPv6: 2620:0:2d0:200::10
IPv4: 192.0.32.10

You need to use the getHostByName() function in the C++ sockets library. 您需要在C ++套接字库中使用getHostByName()函数。 ( here is an example ) 这是一个例子

It will give you back a hostent struct, from which you can get information like IP. 它将带给您一个宿主结构,您可以从中获得IP等信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM