C++实现DNS域名解析(四)

2014-11-24 13:28:51 · 作者: · 浏览: 367
ulTimeSpent)
159 {
160 ULONG ulSendTimestamp = GetTickCountCalibrate();
161
162 if (pveculIPList != NULL)
163 {
164 pveculIPList->clear();
165 }
166 if (pvecstrCNameList != NULL)
167 {
168 pvecstrCNameList->clear();
169 }
170
171 char recvbuf[1024] = {'\0'};
172 char szDotName[128] = {'\0'};
173 USHORT nEncodedNameLen = 0;
174
175 while (TRUE)
176 {
177 if (WSAWaitForMultipleEvents(1, &m_event, FALSE, 100, FALSE) != WSA_WAIT_TIMEOUT)
178 {
179 WSANETWORKEVENTS netEvent;
180 WSAEnumNetworkEvents(m_sock, m_event, &netEvent);
181
182 if (netEvent.lNetworkEvents & FD_READ)
183 {
184 ULONG ulRecvTimestamp = GetTickCountCalibrate();
185 int nSockaddrDestSize = sizeof(sockAddrDNSServer);
186
187 //接收响应报文
188 if (recvfrom(m_sock, recvbuf, 1024, 0, (struct sockaddr*)&sockAddrDNSServer, &nSockaddrDestSize) != SOCKET_ERROR)
189 {
190 DNSHeader *pDNSHeader = (DNSHeader*)recvbuf;
191 USHORT usQuestionCount = 0;
192 USHORT usAnswerCount = 0;
193
194 if (pDNSHeader->usTransID == m_usCurrentProcID
195 && (ntohs(pDNSHeader->usFlags) & 0xfb7f) == 0x8100 //RFC1035 4.1.1(Header section format)
196 && (usQuestionCount = ntohs(pDNSHeader->usQuestionCount)) >= 0
197 && (usAnswerCount = ntohs(pDNSHeader->usAnswerCount)) > 0)
198 {
199 char *pDNSData = recvbuf + sizeof(DNSHeader);
200
201 //解析Question字段
202 for (int q = 0; q != usQuestionCount; ++q)
203 {
204 if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, sizeof(szDotName)))
205 {
206 return FALSE;
207 }
208 pDNSData += (nEncodedNameLen + DNS_TYPE_SIZE + DNS_CLASS_SIZE);
209 }
210
211 //解析Answer字段
212 for (int a = 0; a != usAnswerCount; ++a)
213 {
214 if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, sizeof(szDotName), recvbuf))
215 {
216 return FALSE;
217 }
218 pDNSData += nEncodedNameLen;
219
220 USHORT usAnswerType = ntohs(*(USHORT*)(pDNSData));
221 USHORT usAnswerClass = ntohs(*(USHORT*)(pDNSData + DNS_TYPE_SIZE));
222 ULONG usAnswerTTL = ntohl(*(ULONG*)(pDNSData + DNS_TYPE_SIZE + DNS_CLASS_SIZE));
223 USHORT usAnswerDataLen = ntohs(*(USHORT*)(pDNSData + DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE));
224 pDNSData += (DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE + DNS_DATALEN_SIZE);
225
226 if (usAnswerType == DNS_TYPE_A && pveculIPList != NULL)
227 {
228 ULONG ulIP = *(ULONG*)(pDNSData);
229 pveculIPList->push_back(ulIP);
230 }
231 else if (usAnswerType == DNS_TYPE_CNAME && pvecstrCNameList != NULL)
232 {
233 if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, s