Pulling MX record from DNS server

前端 未结 5 1197
既然无缘
既然无缘 2021-01-02 08:35

I am writing an application that is requiring me to do a DNS lookup for an MX record. I\'m not sure if anyone has had experience doing this kind of work but if you do, any

5条回答
  •  情歌与酒
    2021-01-02 08:57

    The simplest method is to simply use commonly available tools.

    The basic "dig" command will return the records to you via this query:

    dig mx example.com
    

    If you want just the lines with the mx records...

    dig mx example.com | grep -v '^;' | grep example.com
    

    dig is available on most linux / unix boxes.

    If you're on windows you can use nslookup

    nslookup -type=mx example.com
    

    Then just parse the output of these common tools.

    EDIT: Simple C example of sockets from the web

    Since you put "C" as a tag, I guess you're looking for source code to do MX lookups using raw sockets. I copied this from http://www.developerweb.net/forum/showthread.php?t=3550. It may be more what you're looking for?

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main (int argc, char *argv[])
    {
        u_char nsbuf[4096];
        char dispbuf[4096];
        ns_msg msg;
        ns_rr rr;
        int i, j, l;
    
        if (argc < 2) {
            printf ("Usage: %s [...]\n", argv[0]);
            exit (1);
        }
    
        for (i = 1; i < argc; i++) {
            l = res_query (argv[i], ns_c_any, ns_t_mx, nsbuf, sizeof (nsbuf));
            if (l < 0) {
                perror (argv[i]);
            } else {
    #ifdef USE_PQUERY
    /* this will give lots of detailed info on the request and reply */
                res_pquery (&_res, nsbuf, l, stdout);
    #else
    /* just grab the MX answer info */
                ns_initparse (nsbuf, l, &msg);
                printf ("%s :\n", argv[i]);
                l = ns_msg_count (msg, ns_s_an);
                for (j = 0; j < l; j++) {
                    ns_parserr (&msg, ns_s_an, j, &rr);
                    ns_sprintrr (&msg, &rr, NULL, NULL, dispbuf, sizeof (dispbuf));
                    printf ("%s\n", dispbuf);
                }
    #endif
            }
        }
    
        exit (0);
    }
    

提交回复
热议问题