在C linux中查询MX记录

时间:2009-11-06 15:48:15

标签: c linux smtp dns

Linux上的C中是否有任何函数可以查询MX记录(如gethostbyname)。?

2 个答案:

答案 0 :(得分:7)

-lresolv(BIND的libresolv)链接。

#include <arpa/inet.h>
#include <resolv.h>
#include <string.h>

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;
}

答案 1 :(得分:1)

我只想补充上面的答案。我收到了编译错误。经过搜索,我在一个论坛上找到了如何编译。首先使用main函数(例如gmail.com)

main(){
char *mxs[10];
int a;
printf("%d\n",a=resolvmx("gmail.com",mxs,10));
printf("%s\n",mxs[a-1]);
}

然后将其编译为

gcc <pname.c> /usr/lib/libresolv.a   (instead of gcc pname.c -lresolv)