Possible Duplicate:
Get MX record via C program.
Is there any function in C on linux by which we can query MX record (like gethostbyname).?
Possible Duplicate:
Get MX record via C program.
Is there any function in C on linux by which we can query MX record (like gethostbyname).?
Link with -lresolv
(BIND's 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;
}
I just want to add to the above answer. I was getting compilation errors. After searching, I got at one forum on how to compile. First Use main function as (for say gmail.com)
main(){
char *mxs[10];
int a;
printf("%d\n",a=resolvmx("gmail.com",mxs,10));
printf("%s\n",mxs[a-1]);
}
and then Compile it as
gcc <pname.c> /usr/lib/libresolv.a (instead of gcc pname.c -lresolv)