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 /* minimum possible size of MX record in packet */
23 #define MIN_MX_SIZE 8 /* corresp to "a.com 0" w/ terminating space */
25 struct mxentry *getmxrecords(name)
26 /* get MX records for given host */
29 unsigned char answer[PACKETSZ], *eom, *cp, *bp;
30 int n, ancount, qdcount, buflen, type, pref, ind;
31 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / MIN_MX_SIZE];
32 static char MXHostBuf[PACKETSZ - HFIXEDSZ];
35 n = res_search(name,C_IN,T_MX,(unsigned char*)&answer, sizeof(answer));
37 return((struct mxentry *)NULL);
39 hp = (HEADER *)&answer;
40 cp = answer + HFIXEDSZ;
43 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
44 if ((n = dn_skipname(cp, eom)) < 0)
45 return((struct mxentry *)NULL);
46 buflen = sizeof(MXHostBuf) - 1;
49 ancount = ntohs(hp->ancount);
50 while (--ancount >= 0 && cp < eom)
52 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
56 cp += INT16SZ + INT32SZ;
64 if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
79 pmx[ind].name = (char *)NULL;
83 #endif /* HAVE_GETHOSTBYNAME */
86 main(int argc, char *argv[])
89 struct mxentry *responses;
91 responses = getmxrecords(argv[1]);
92 if (responses == (struct mxentry *)NULL)
93 puts("No MX records found");
96 printf("%s %d\n", responses->name, responses->pref);
98 ((++responses)->name);
100 #endif /* TESTMAIN */
102 /* mxget.c ends here */