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.
10 #ifdef HAVE_RES_SEARCH
12 #ifdef HAVE_NET_SOCKET_H
13 #include <net/socket.h>
16 #include <sys/types.h>
17 #include <netinet/in.h>
20 #include "beos/beos_nameser.h"
23 #ifdef HAVE_ARPA_NAMESER_H
24 #include <arpa/nameser.h>
33 * This ought to be in the bind library. It's adapted from sendmail.
37 * These are defined in RFC833. Some bind interface headers don't declare them.
38 * Ghod help us if they're ever actually incompatible with what's in
39 * the arpa/nameser.h header.
42 #define PACKETSZ 512 /* maximum packet size */
45 #define HFIXEDSZ 12 /* #/bytes of fixed data in header */
48 #define INT32SZ 4 /* for systems without 32-bit ints */
51 #define INT16SZ 2 /* for systems without 16-bit ints */
54 /* minimum possible size of MX record in packet */
55 #define MIN_MX_SIZE 8 /* corresp to "a.com 0" w/ terminating space */
57 struct mxentry *getmxrecords(const char *name)
58 /* get MX records for given host */
60 char answer[PACKETSZ], *eom, *cp, *bp;
61 int n, ancount, qdcount, buflen, type, pref, ind;
62 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / MIN_MX_SIZE];
63 static char MXHostBuf[PACKETSZ - HFIXEDSZ];
66 pmx->name = (char *)NULL;
68 n = res_search(name, C_IN,T_MX, (unsigned char *)&answer, sizeof(answer));
70 return((struct mxentry *)NULL);
71 if ((size_t)n > sizeof(answer))
74 hp = (HEADER *)&answer;
75 cp = answer + HFIXEDSZ;
78 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
79 if ((n = dn_skipname((unsigned char *)cp, (unsigned char *)eom)) < 0)
80 return((struct mxentry *)NULL);
81 buflen = sizeof(MXHostBuf) - 1;
84 ancount = ntohs(hp->ancount);
85 while (--ancount >= 0 && cp < eom)
87 if ((n = dn_expand((unsigned char *)answer, (unsigned char *)eom,
88 (unsigned char *)cp, bp, buflen)) < 0)
92 cp += INT16SZ + INT32SZ;
100 if ((n = dn_expand((unsigned char *)answer, (unsigned char *)eom,
101 (unsigned char *)cp, bp, buflen)) < 0)
106 pmx[ind].pref = pref;
109 n = strlen((const char *)bp);
116 pmx[ind].name = (char *)NULL;
120 #endif /* HAVE_RES_SEARCH */
125 int main(int argc, char *argv[])
127 struct mxentry *responses;
129 if (argc != 2 || 0 == strcmp(argv[1], "-h")) {
130 fprintf(stderr, "Usage: %s domain\n", argv[0]);
134 #ifdef HAVE_RES_SEARCH
135 responses = getmxrecords(argv[1]);
136 if (responses == (struct mxentry *)NULL) {
137 puts("No MX records found");
140 printf("%s %d\n", responses->name, responses->pref);
141 } while ((++responses)->name);
144 puts("This program was compiled without HAS_RES_SEARCH and does nothing.");
149 #endif /* TESTMAIN */
151 /* mxget.c ends here */