-
-
Save sumantro93/2ccb1a30b582956f55e5b04b319cfaa5 to your computer and use it in GitHub Desktop.
c-ares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <ares.h> | |
#include <arpa/inet.h> | |
#include <netdb.h> | |
void callback(void *arg, int status, int timeouts, struct hostent *host) { | |
if (status == ARES_SUCCESS) { | |
char ip[INET6_ADDRSTRLEN]; | |
int idx; | |
for (idx = 0; host->h_addr_list[idx]; ++idx) { | |
inet_ntop(host->h_addrtype, host->h_addr_list[idx], ip, sizeof(ip)); | |
printf("%s\n", ip); | |
} | |
} else { | |
printf("Failed to lookup: %s\n", ares_strerror(status)); | |
} | |
} | |
int main(int argc, char **argv) { | |
ares_channel channel; | |
int nfds, rv; | |
fd_set read_fds, write_fds; | |
struct timeval *tvp, tv; | |
if (ares_library_init(ARES_LIB_INIT_ALL)) { | |
return 1; // Initialization failure | |
} | |
if (ares_init(&channel) != ARES_SUCCESS) { | |
ares_library_cleanup(); | |
return 1; // Initialization failure | |
} | |
ares_gethostbyname(channel, "www.google.com", AF_INET, callback, NULL); | |
while (1) { | |
FD_ZERO(&read_fds); | |
FD_ZERO(&write_fds); | |
nfds = ares_fds(channel, &read_fds, &write_fds); | |
if (nfds == 0) { | |
break; // All queries completed | |
} | |
tvp = ares_timeout(channel, NULL, &tv); | |
rv = select(nfds, &read_fds, &write_fds, NULL, tvp); | |
if (rv < 0) { | |
printf("Error in select()\n"); | |
ares_cancel(channel); | |
} else if (rv == 0) { | |
ares_process(channel, NULL, NULL); // Timeout | |
} else { | |
ares_process(channel, &read_fds, &write_fds); // Process results | |
} | |
} | |
ares_destroy(channel); | |
ares_library_cleanup(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment