Skip to content

Instantly share code, notes, and snippets.

@sumantro93
Last active August 13, 2023 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumantro93/2ccb1a30b582956f55e5b04b319cfaa5 to your computer and use it in GitHub Desktop.
Save sumantro93/2ccb1a30b582956f55e5b04b319cfaa5 to your computer and use it in GitHub Desktop.
c-ares
#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