最简单的方法是简单地使用常用的工具。
基本的“dig”命令将通过以下查询将记录返回给您:
dig mx example.com
如果您只想要包含 mx 记录的行...
dig mx example.com | grep -v '^;' | grep example.com
dig 可在大多数 linux / unix 机器上使用。
如果您使用的是 Windows,则可以使用 nslookup
nslookup -type=mx example.com
然后只需解析这些常用工具的输出即可。
编辑:来自网络的套接字的简单 C 示例
由于您将“C”作为标签,我猜您正在寻找使用原始套接字进行 MX 查找的源代码。我复制了这个http://www.developerweb.net/forum/showthread.php?t=3550。这可能是您正在寻找的更多内容?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <resolv.h>
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 <domain>[...]\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);
}