- 论坛徽章:
- 0
|
/***************************************************************************
smtp.h - description
-------------------
begin : 2003.06.25
copyright : (C) 2003 by 小东(chinlone@163.com) GPL版权
email : chinlone@163.com
***************************************************************************/
/***************************************************************************
GPL软件授权.
函数返回值: -1(出错),否则为MX记录的条数
函数使用方法:将此头文件包含后
char *hosts[MAXMXHOSTS];
char *host; /* host name */
host = "163.com";
int n = getmxrr(host, hosts); /* 开始调用函数 */
if(n<0) printf("Can't get MX!" ;
/* 打印MX列表 */
else
{
int i = 0;
while(i<n)
{
printf("%s\n",hosts);
i++;
}
}
***************************************************************************/
#include <resolv.h>;
#define MAXMXHOSTS 20
int getmxrr(char *hostname, char *mxhosts[])
{
static char *commonBufferPoint;
char *index ();
int n; /* utility index */
HEADER *dhp; /* DNS reply header and fields*/
int ancount;
int qdcount;
union /* DNS reply and pointers */
{
HEADER hdr;
u_char bytes[PACKETSZ]; /* hostnames buffer PACKETSZ = 512 */
} answer;
u_char *cp;
u_char *eom;
char hostbuf[PACKETSZ]; /* hostnames buffer PACKETSZ = 512 */
int buflen;
u_short pref;
u_short type;
u_short prefs[MAXMXHOSTS];
u_long bestpref;
int i;
if (res_init() < 0) return -1;
n = res_search(hostname, C_IN, T_MX, answer.bytes, sizeof (answer));
if (n < 0) return -1;
/* find first answer */
dhp = &answer.hdr;
cp = answer.bytes + sizeof (HEADER);
eom = answer.bytes + n;
for (qdcount = ntohs (dhp->;qdcount); qdcount--; cp += n + QFIXEDSZ)
/* Skip domain name, get class, and type. */
if ((n = dn_skipname (cp, eom)) < 0) return -1;
/* copy MX hosts and preferences into arrays */
buflen = sizeof (hostbuf);
commonBufferPoint = hostbuf;
ancount = ntohs (dhp->;ancount);
i = 0;
while (--ancount >;= 0 && cp < eom && i < MAXMXHOSTS)
{
if ((n = dn_expand (&answer.hdr, eom, cp, commonBufferPoint, buflen)) < 0) return -1;
/* printf("dn_expand error:%s\n", hstrerror(errno)); */
cp += n;
GETSHORT (type, cp);
cp += sizeof (u_short) + sizeof (u_long);
GETSHORT (n, cp);
if (type != T_MX)
{
cp += n;
continue;
}
GETSHORT (pref, cp);
if ((n = dn_expand (&answer.hdr, eom, cp, commonBufferPoint, buflen)) < 0) return -1;
cp += n;
prefs = pref;
mxhosts = commonBufferPoint;
i++;
n = strlen (commonBufferPoint) + 1;
commonBufferPoint += n;
buflen -= n;
}
return i;
}; |
|