Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying MX record in C linux

Tags:

c

linux

smtp

dns

Is there any function in C on linux by which we can query MX record (like gethostbyname).?

like image 432
avd Avatar asked Nov 06 '09 15:11

avd


People also ask

How do I find MX records in Linux?

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.

What is MX record Linux?

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.


Video Answer


2 Answers

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;
}
like image 173
ephemient Avatar answered Sep 26 '22 01:09

ephemient


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)
like image 27
avd Avatar answered Sep 26 '22 01:09

avd