Reputation: 1031
In my C++ linux application how can I get the IPs list reffering to an FQDN? (static IPs + dynamic IPs)
10x
Upvotes: 0
Views: 1064
Reputation: 287825
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
Upvotes: 2
Reputation: 715
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.
Upvotes: 0