2 * mxget.c -- fetch MX records for given DNS name
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
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.
23 * These are defined in RFC833. Some bind interface headers don't declare them.
24 * Ghod help us if they're ever actually incompatible with what's in
25 * the arpa/nameser.h header.
28 #define PACKETSZ 512 /* maximum packet size */
31 #define HFIXEDSZ 12 /* #/bytes of fixed data in header */
34 #define INT32SZ 4 /* for systems without 32-bit ints */
37 #define INT16SZ 2 /* for systems without 16-bit ints */
40 /* minimum possible size of MX record in packet */
41 #define MIN_MX_SIZE 8 /* corresp to "a.com 0" w/ terminating space */
43 struct mxentry *getmxrecords(const char *name)
44 /* get MX records for given host */
46 char answer[PACKETSZ], *eom, *cp, *bp;
47 int n, ancount, qdcount, buflen, type, pref, ind;
48 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / MIN_MX_SIZE];
49 static char MXHostBuf[PACKETSZ - HFIXEDSZ];
52 pmx->name = (char *)NULL;
54 n = res_search(name, C_IN,T_MX, (unsigned char *)&answer, sizeof(answer));
56 return((struct mxentry *)NULL);
58 hp = (HEADER *)&answer;
59 cp = answer + HFIXEDSZ;
62 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
63 if ((n = dn_skipname(cp, eom)) < 0)
64 return((struct mxentry *)NULL);
65 buflen = sizeof(MXHostBuf) - 1;
68 ancount = ntohs(hp->ancount);
69 while (--ancount >= 0 && cp < eom)
71 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
75 cp += INT16SZ + INT32SZ;
83 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
91 n = strlen((const char *)bp);
98 pmx[ind].name = (char *)NULL;
102 #endif /* HAVE_RES_SEARCH */
105 main(int argc, char *argv[])
108 struct mxentry *responses;
110 responses = getmxrecords(argv[1]);
111 if (responses == (struct mxentry *)NULL)
112 puts("No MX records found");
115 printf("%s %d\n", responses->name, responses->pref);
117 ((++responses)->name);
119 #endif /* TESTMAIN */
121 /* mxget.c ends here */