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

2014-11-24 13:28:51 · 作者: · 浏览: 361
izeof(szDotName), recvbuf))
234 {
235 return FALSE;
236 }
237 pvecstrCNameList->push_back(szDotName);
238 }
239
240 pDNSData += (usAnswerDataLen);
241 }
242
243 //计算DNS查询所用时间
244 if (pulTimeSpent != NULL)
245 {
246 *pulTimeSpent = ulRecvTimestamp - ulSendTimestamp;
247 }
248
249 break;
250 }
251 }
252 }
253 }
254
255 //超时退出
256 if (GetTickCountCalibrate() - ulSendTimestamp > ulTimeout)
257 {
258 *pulTimeSpent = ulTimeout + 1;
259 return FALSE;
260 }
261 }
262
263 return TRUE;
264 }
265
266 /*
267 * convert "www.baidu.com" to "\x03www\x05baidu\x03com"
268 * 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
269 */
270 BOOL CDNSLookup::EncodeDotStr(char *szDotStr, char *szEncodedStr, USHORT nEncodedStrSize)
271 {
272 USHORT nDotStrLen = strlen(szDotStr);
273
274 if (szDotStr == NULL || szEncodedStr == NULL || nEncodedStrSize < nDotStrLen + 2)
275 {
276 return FALSE;
277 }
278
279 char *szDotStrCopy = new char[nDotStrLen + 1];
280 //strcpy_s(szDotStrCopy, nDotStrLen + 1, szDotStr);
281 strcpy(szDotStrCopy, szDotStr);
282
283 char *pNextToken = NULL;
284 //char *pLabel = strtok_s(szDotStrCopy, ".", &pNextToken);
285 char *pLabel = strtok(szDotStrCopy, ".");
286 USHORT nLabelLen = 0;
287 USHORT nEncodedStrLen = 0;
288 while (pLabel != NULL)
289 {
290 if ((nLabelLen = strlen(pLabel)) != 0)
291 {
292 //sprintf_s(szEncodedStr + nEncodedStrLen, nEncodedStrSize - nEncodedStrLen, "%c%s", nLabelLen, pLabel);
293 sprintf(szEncodedStr + nEncodedStrLen, "%c%s", nLabelLen, pLabel);
294 nEncodedStrLen += (nLabelLen + 1);
295 }
296 //pLabel = strtok_s(NULL, ".", &pNextToken);
297 pLabel = strtok(NULL, ".");
298 }
299
300 delete [] szDotStrCopy;
301
302 return TRUE;
303 }
304
305 /*
306 * convert "\x03www\x05baidu\x03com\x00" to "www.baidu.com"
307 * 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
308 * convert "\x03www\x05baidu\xc0\x13" to "www.baidu.com"
309 * 0x0000 03 77 77 77 05 62 61 69 64 75 c0 13 ff ff ff ff
310 * 0x0010 ff ff ff 03 63 6f 6d 00 ff ff ff ff ff ff ff ff
311 */
312 BOOL CDNSLookup::DecodeDotStr(char *szEncodedStr, USHORT *pusEncodedStrLen, char *szDotStr, USHORT nDotStrSize, char *szPacketStartPos)
313 {
314 if (szEncodedStr == NULL || pusEncodedStrLen == NULL || szDotStr == NULL)
315 {
316 return FALSE;
317 }
318
319 char *pDecodePos = szEncodedStr;
320 USHORT usPlainStrLen = 0;
321 BYTE nLabelDataLen = 0;
322 *pusEncodedStrLen = 0;
323
324 while ((nLabelDataLen = *pDecodePos) != 0x00)
325 {
326 if ((nLabelDataLen & 0xc0) == 0) //普通格式,LabelDataLen + Label
327 {
328 if (usPlainStrLen + nLabelDataLen + 1 > nDotStrSize)
329 {
330 return FALSE;
331 }
332 memcpy(szDotStr + usPlainStrLen, pDecodePos + 1, nLabelDataLen);
333 memcpy(szDotStr + usPlainStrLen + nLabelDataLen, ".", 1);
334