1 /* Async DNS lookup. Shows passing complex data through pool. */
2 #include <ccan/antithread/antithread.h>
3 #include <ccan/str/str.h>
4 #include <ccan/talloc/talloc.h>
6 #include <sys/select.h>
11 struct lookup_answer {
15 int herrno; /* If !ok */
19 /* Including NULL terminator. */
20 static inline unsigned count_entries(char **entries)
24 for (i = 0; entries[i]; i++);
28 /* Copy as one nice tallocated object. Since ans is in the pool, it
29 * all gets put in the pool. */
30 static void copy_answer(struct lookup_answer *ans, const struct hostent *host)
34 ans->hent.h_name = talloc_strdup(ans, host->h_name);
35 ans->hent.h_aliases = talloc_array(ans, char *,
36 count_entries(host->h_aliases));
37 for (i = 0; host->h_aliases[i]; i++)
38 ans->hent.h_aliases[i] = talloc_strdup(ans->hent.h_aliases,
40 ans->hent.h_aliases[i] = NULL;
41 ans->hent.h_addrtype = host->h_addrtype;
42 ans->hent.h_length = host->h_length;
43 ans->hent.h_addr_list = talloc_array(ans, char *,
44 count_entries(host->h_addr_list));
45 for (i = 0; host->h_addr_list[i]; i++)
46 ans->hent.h_addr_list[i] = talloc_memdup(ans->hent.h_addr_list,
51 static void *lookup_dns(struct at_pool *atp, char *name)
53 struct lookup_answer *ans;
56 host = gethostbyname(name);
58 ans = talloc(at_pool_ctx(atp), struct lookup_answer);
61 ans->herrno = h_errno;
64 copy_answer(ans, host);
70 static void report_answer(const char *name, const struct lookup_answer *ans)
75 printf("%s: %s\n", name, hstrerror(ans->herrno));
80 for (i = 0; ans->hent.h_aliases[i]; i++)
81 printf("%c%s", i == 0 ? '[' : ' ', ans->hent.h_aliases[i]);
84 printf("%#x", ans->hent.h_addrtype);
85 for (i = 0; ans->hent.h_addr_list[i]; i++) {
88 for (j = 0; j < ans->hent.h_length; j++)
89 printf("%02x", ans->hent.h_addr_list[i][j]);
94 int main(int argc, char *argv[])
101 errx(1, "Usage: dns_lookup [--sync] name...");
103 /* Give it plenty of room. */
104 atp = at_pool(argc * 1024*1024);
106 err(1, "Can't create pool");
108 /* Free pool on exit. */
109 talloc_steal(talloc_autofree_context(), atp);
111 if (streq(argv[1], "--sync")) {
112 for (i = 2; i < argc; i++) {
113 struct lookup_answer *ans = lookup_dns(atp, argv[i]);
114 report_answer(argv[i], ans);
120 at = talloc_array(atp, struct athread *, argc);
122 for (i = 1; i < argc; i++) {
123 at[i] = at_run(atp, lookup_dns, argv[i]);
125 err(1, "Can't spawn child");
128 for (i = 1; i < argc; i++) {
129 struct lookup_answer *ans = at_read(at[i]);
131 warn("Child died on '%s'", argv[i]);
133 report_answer(argv[i], ans);