www.pudn.com > FindMail.zip > DNSClient.cpp


#include "StdAfx.h" 
#include "iphlpapi.h" 
#include "DNSClient.h" 
#include "udp.h" 
#include "util.h" 
 
CDNSClient::CDNSClient(void) 
: m_mx_server_count(0) 
, m_mx_servers(NULL) 
, m_dns_count(0) 
, m_dns_servers(NULL) 
{ 
	GetDNS(); 
} 
 
CDNSClient::~CDNSClient(void) 
{ 
	FreeMxServers(); 
	FreeDnsServers(); 
} 
 
int CDNSClient::GetMxServers(char * domain_name) 
{ 
	// 使用UDP查询结果 
	int sd =udp_connect(m_dns_ip, 53); 
	if(sd <0) 
		return -1; 
	FreeMxServers(); 
	char buf[512]; 
	memset(buf, 0, sizeof(buf)); 
	buf[0] =0; 
	buf[1] =1;  // 序号 
	buf[2] =1;  // 查询 
	buf[3] =buf[4] =0; 
	buf[5] =1;  // 1个问题 
	char dm[100]; 
	strcpy(dm, domain_name); 
	char *p =dm; 
	char *p1 =strchr(p, '.'); 
	int pos =12; 
 
	while(p) 
	{ 
		if(p1) *p1 =0; 
		buf[pos] =(char)strlen(p); 
		strcpy(&buf[pos+1], p); 
		pos +=(char)(strlen(p)+1); 
		if(p1) 
		{ 
			p =p1+1; 
			p1 =strchr(p, '.'); 
		} 
		else p =NULL; 
	} 
	buf[pos++] =0; 
	buf[pos++] =0; 
	buf[pos++] =15; 
	buf[pos++] =0; 
	buf[pos++] =1; 
 
	udp_send(sd, buf, sizeof(buf)); 
	int len =udp_recv(sd, buf, sizeof(buf), 20);	 
	udp_close(sd); 
	if(len <0) 
		return -1; 
	int qcount =(buf[4] & 0x00FF << 8) | (buf[5] & 0x00FF);  // 问题数 
	if(qcount <0) 
		return 0; 
	int acount =(buf[6] & 0xFF << 8) | (buf[7] & 0x00FF); 
	if(acount <0) 
		return 0; 
	 
	pos =12; 
	int i; 
	//WriteBinData(buf, len); 
	for(i =0; iDnsServerList; 
	while(pIPAddr) 
	{ 
		AddDnsServer(pIPAddr->IpAddress.String); 
		pIPAddr =pIPAddr->Next; 
	} 
	if(pfixed_info->CurrentDnsServer) 
		strcpy(m_dns_ip, pfixed_info->CurrentDnsServer->IpAddress.String); 
	else strcpy(m_dns_ip, m_dns_servers[0]); 
 
	free(pfixed_info); 
	 
	return 0; 
} 
 
int CDNSClient::FreeMxServers(void) 
{ 
	if(m_mx_servers ==NULL || m_mx_server_count <=0) return 0; 
 
	for(int i =0; i512) return -1; 
		pos ++; 
		if((len & 0xc0) ==0xc0)  // 压缩格式 
		{ 
			int offset =((len & 0x3f) << 8) | (buf[pos++] & 0xff); 
			SkipString(buf, offset, domain_name); 
			return pos; 
		} 
		else 
		{ 
			int len2 =(int)strlen(domain_name); 
			strncat(domain_name, &buf[pos], len); 
			domain_name[len2+len] =0; 
			pos +=len; 
		} 
		 
		if(buf[pos]) strcat(domain_name, "."); 
		len =buf[pos]; 
	} 
 
	return pos+1; 
} 
 
int CDNSClient::FreeDnsServers(void) 
{ 
	if(m_dns_servers ==NULL || m_dns_count <=0) return 0; 
 
	for(int i =0; i