链接-lresolv(BIND的libresolv)。
#include
#include
#include
int resolvmx(const char *name, char **mxs, int limit) {
unsigned char response[NS_PACKETSZ]; /* big enough, right? */
ns_msg handle;
ns_rr rr;
int mx_index, ns_index, len;
char dispbuf[4096];
if ((len = res_search(name, C_IN, T_MX, response, sizeof(response))) < 0) {
/* WARN: res_search failed */
return -1;
}
if (ns_initparse(response, len, &handle) < 0) {
/* WARN: ns_initparse failed */
return 0;
}
len = ns_msg_count(handle, ns_s_an);
if (len < 0)
return 0;
for (mx_index = 0, ns_index = 0;
mx_index < limit && ns_index < len;
ns_index++) {
if (ns_parserr(&handle, ns_s_an, ns_index, &rr)) {
/* WARN: ns_parserr failed */
continue;
}
ns_sprintrr (&handle, &rr, NULL, NULL, dispbuf, sizeof (dispbuf));
if (ns_rr_class(rr) == ns_c_in && ns_rr_type(rr) == ns_t_mx) {
char mxname[MAXDNAME];
dn_expand(ns_msg_base(handle), ns_msg_base(handle) + ns_msg_size(handle), ns_rr_rdata(rr) + NS_INT16SZ, mxname, sizeof(mxname));
mxs[mx_index++] = strdup(mxname);
}
}
return mx_index;
}