Is there any function in C on linux by which we can query MX record (like gethostbyname).?
The best way to check MX record in Linux is using dig command. Open the terminal and type dig domain name mx. It will return all the MX records of this domain. For example, dig example.com mx +answer will output the MX records for domain example.com.
An MX (mail exchange) record is an entry in your DNS. zone file which specifies a mail server to handle a domain's email. You must configure an MX recordMail Exchanger record is a record in DNS that specifies which server is handles email messages. to receive email to your domain.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With