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.
13 #include <sys/types.h>
14 #include <netinet/in.h>
15 #include <arpa/nameser.h>
20 * This ought to be in the bind library. It's adapted from sendmail.
24 * These are defined in RFC833. Some bind interface headers don't declare them.
25 * Ghod help us if they're ever actually incompatible with what's in
26 * the arpa/nameser.h header.
29 #define PACKETSZ 512 /* maximum packet size */
32 #define HFIXEDSZ 12 /* #/bytes of fixed data in header */
35 #define INT32SZ 4 /* for systems without 32-bit ints */
38 #define INT16SZ 2 /* for systems without 16-bit ints */
41 /* minimum possible size of MX record in packet */
42 #define MIN_MX_SIZE 8 /* corresp to "a.com 0" w/ terminating space */
44 struct mxentry *getmxrecords(const char *name)
45 /* get MX records for given host */
47 char answer[PACKETSZ], *eom, *cp, *bp;
48 int n, ancount, qdcount, buflen, type, pref, ind;
49 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / MIN_MX_SIZE];
50 static char MXHostBuf[PACKETSZ - HFIXEDSZ];
53 pmx->name = (char *)NULL;
55 n = res_search(name, C_IN,T_MX, (unsigned char *)&answer, sizeof(answer));
57 return((struct mxentry *)NULL);
59 hp = (HEADER *)&answer;
60 cp = answer + HFIXEDSZ;
63 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
64 if ((n = dn_skipname(cp, eom)) < 0)
65 return((struct mxentry *)NULL);
66 buflen = sizeof(MXHostBuf) - 1;
69 ancount = ntohs(hp->ancount);
70 while (--ancount >= 0 && cp < eom)
72 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
76 cp += INT16SZ + INT32SZ;
84 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
92 n = strlen((const char *)bp);
99 pmx[ind].name = (char *)NULL;
103 #endif /* HAVE_RES_SEARCH */
106 main(int argc, char *argv[])
109 struct mxentry *responses;
111 responses = getmxrecords(argv[1]);
112 if (responses == (struct mxentry *)NULL)
113 puts("No MX records found");
116 printf("%s %d\n", responses->name, responses->pref);
118 ((++responses)->name);
120 #endif /* TESTMAIN */
122 /* mxget.c ends here */