简体   繁体   中英

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? (static IPs + dynamic IPs)

10x

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. 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. For example, google.com will usually map to servers on your continent.

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. ( here is an example )

It will give you back a hostent struct, from which you can get information like IP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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