2 * mxget.c -- fetch MX records for given DNS name
4 * Copyright 1996 by Eric S. Raymond
6 * For license terms, see the file COPYING in this directory.
10 #ifdef HAVE_GETHOSTBYNAME
12 #include <sys/types.h>
13 #include <netinet/in.h>
14 #include <arpa/nameser.h>
19 * This ought to be in the bind library. It's adapted from sendmail.
22 struct mxentry *getmxrecords(name)
23 /* get MX records for given host */
26 unsigned char answer[PACKETSZ], MXHostBuf[PACKETSZ], *eom, *cp, *bp;
27 int n, ancount, qdcount, buflen, type, pref, ind;
28 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / sizeof(struct mxentry)];
31 n = res_search(name,C_IN,T_MX,(unsigned char*)&answer, sizeof(answer));
33 return((struct mxentry *)NULL);
35 hp = (HEADER *)&answer;
36 cp = answer + HFIXEDSZ;
39 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
40 if ((n = dn_skipname(cp, eom)) < 0)
41 return((struct mxentry *)NULL);
42 buflen = sizeof(MXHostBuf) - 1;
45 ancount = ntohs(hp->ancount);
46 while (--ancount >= 0 && cp < eom)
48 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
52 cp += INT16SZ + INT32SZ;
60 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
75 pmx[ind].name = (char *)NULL;
79 #endif /* HAVE_GETHOSTBYNAME */
82 main(int argc, char *argv[])
85 struct mxentry *responses;
87 responses = getmxrecords(argv[1]);
88 if (responses == (struct mxentry *)NULL)
89 puts("No MX records found");
92 printf("%s %d\n", responses->name, responses->pref);
94 ((++responses)->name);
98 /* mxget.c ends here */