VC.DNS解析(winsock)
1、尝试了 gethostbyname(...) 和 Qt598中的qhostinfo::fromname(...),都可以解析出来IP,但是有一个问题:域名指向的IP改变了,这两种方式需要等较长时间 才会解析到更新后的ip地址。而CMD中 nslookup却一下子就解析到了更新后的IP...
1.1、查了一下资料,貌似原因如下(大概的说下原理,可能不严谨准确):
(1)域名服务器在 域名的TTL时间段内 它不会去实时的查找域名对应的IP,而是要等到TTL超时 域名服务器才回去再次查询 然后更新新的地址。
(2)又∵ gethostbyname 和 qhostinfo::fromname 都没有参数可以输入 DNS服务器地址,猜测可能使用的是 OS中设置的DNS服务器。
ZC:综上2个原因 造成了这个现象
ZC:改 OS的DNS设置的话,如果 这个DNS服务器不是 常用上网的DNS服务器的话,到时候还要改回来,比较麻烦,暂不考虑使用
1.2、于是猜测,指定 DNS解析服务器的话,就能解决这个现象
2、C++实现DNS域名解析 - Snser - 博客园.html(https://www.cnblogs.com/snser/p/4101729.html)
ZC:DNS解析的 数据包结构、原理、代码 都在这个文章中查看
ZC:只解析IPv4地址的精简版代码在 2.2
2.1、这是文章中的代码(少许改动,运行OK)(项目->属性->C/C++->预处理器->"预处理器定义"中添加 "_ITERATOR_DEBUG_LEVEL=0")
(1)CDNSLookup.h
#pragma once // C++实现DNS域名解析 - Snser - 博客园.html (https://www.cnblogs.com/snser/p/4101729.html) #define _CRT_SECURE_NO_WARNINGS //这里需要导入库 Ws2_32.lib,在不同的IDE下可能不太一样
//#pragma comment(lib, "Ws2_32.lib") #include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib") //#include <windows.h>
#include <string>
#include <vector> #define MAX_DOMAINNAME_LEN 255
#define DNS_PORT 53
#define DNS_TYPE_SIZE 2
#define DNS_CLASS_SIZE 2
#define DNS_TTL_SIZE 4
#define DNS_DATALEN_SIZE 2
#define DNS_TYPE_A 0x0001 //1 a host address
#define DNS_TYPE_CNAME 0x0005 //5 the canonical name for an alias
#define DNS_PACKET_MAX_SIZE (sizeof(DNSHeader) + MAX_DOMAINNAME_LEN + DNS_TYPE_SIZE + DNS_CLASS_SIZE) struct DNSHeader
{
USHORT usTransID; //标识符
USHORT usFlags; //各种标志位
USHORT usQuestionCount; //Question字段个数
USHORT usAnswerCount; //Answer字段个数
USHORT usAuthorityCount; //Authority字段个数
USHORT usAdditionalCount; //Additional字段个数
}; class CDNSLookup
{
public:
CDNSLookup();
~CDNSLookup(); BOOL DNSLookup(ULONG ulDNSServerIP, char *szDomainName,
std::vector<ULONG> *pveculIPList = NULL, std::vector<std::string> *pvecstrCNameList = NULL,
ULONG ulTimeout = , ULONG *pulTimeSpent = NULL);
BOOL DNSLookup(ULONG ulDNSServerIP, char *szDomainName,
std::vector<std::string> *pvecstrIPList = NULL, std::vector<std::string>
*pvecstrCNameList = NULL, ULONG ulTimeout = , ULONG *pulTimeSpent = NULL); private:
BOOL Init();
BOOL UnInit(); BOOL DNSLookupCore(ULONG ulDNSServerIP, char *szDomainName, std::vector<ULONG> *pveculIPList, std::vector<std::string> *pvecstrCNameList, ULONG ulTimeout, ULONG *pulTimeSpent);
BOOL SendDNSRequest(sockaddr_in sockAddrDNSServer, char *szDomainName);
BOOL RecvDNSResponse(sockaddr_in sockAddrDNSServer, ULONG ulTimeout,
std::vector<ULONG> *pveculIPList, std::vector<std::string> *pvecstrCNameList, ULONG *pulTimeSpent); BOOL EncodeDotStr(char *szDotStr, char *szEncodedStr, USHORT nEncodedStrSize);
BOOL DecodeDotStr(char *szEncodedStr, USHORT *pusEncodedStrLen, char *szDotStr, USHORT nDotStrSize, char *szPacketStartPos = NULL); private:
BOOL m_bIsInitOK;
SOCKET m_sock;
};
(2)CDNSLookup.cpp
#include "CDNSLookup.h"
#include <stdio.h>
#include <string.h> CDNSLookup::CDNSLookup() :
m_bIsInitOK(FALSE),
m_sock(INVALID_SOCKET)
{
m_bIsInitOK = Init();
} CDNSLookup::~CDNSLookup()
{
UnInit();
} BOOL CDNSLookup::DNSLookup(ULONG ulDNSServerIP, char *szDomainName,
std::vector<ULONG> *pveculIPList, std::vector<std::string> *pvecstrCNameList,
ULONG ulTimeout, ULONG *pulTimeSpent)
{
return DNSLookupCore(ulDNSServerIP, szDomainName, pveculIPList, pvecstrCNameList, ulTimeout, pulTimeSpent);
} BOOL CDNSLookup::DNSLookup(ULONG ulDNSServerIP, char *szDomainName,
std::vector<std::string> *pvecstrIPList, std::vector<std::string> *pvecstrCNameList,
ULONG ulTimeout, ULONG *pulTimeSpent)
{
std::vector<ULONG> *pveculIPList = NULL;
if (pvecstrIPList != NULL)
{
std::vector<ULONG> veculIPList;
pveculIPList = &veculIPList;
} BOOL bRet = DNSLookupCore(ulDNSServerIP, szDomainName, pveculIPList, pvecstrCNameList, ulTimeout, pulTimeSpent); if (bRet)
{
pvecstrIPList->clear();
char szIP[] = { '\0' };
for (std::vector<ULONG>::iterator iter = pveculIPList->begin(); iter != pveculIPList->end(); ++iter)
{
ULONG ul = (*iter);
BYTE *pbyIPSegment = (BYTE*)(&ul);
//BYTE *pbyIPSegment = (BYTE*)(&(*iter));
//sprintf_s(szIP, 16, "%d.%d.%d.%d", pbyIPSegment[0], pbyIPSegment[1], pbyIPSegment[2], pbyIPSegment[3]);
sprintf(szIP, "%d.%d.%d.%d", pbyIPSegment[], pbyIPSegment[], pbyIPSegment[], pbyIPSegment[]);
pvecstrIPList->push_back(szIP);
}
} return bRet;
} BOOL CDNSLookup::Init()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(, ), &wsaData) == SOCKET_ERROR)
{
printf("WSAStartup(...) err : %d\n", ::GetLastError());
return FALSE;
} if ((m_sock = socket(AF_INET, SOCK_DGRAM, )) == INVALID_SOCKET)
{
printf("socket(...) err : %d\n", ::GetLastError());
return FALSE;
} DWORD dwTimeOut = * ;
if (setsockopt(m_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&dwTimeOut, sizeof(dwTimeOut)) == SOCKET_ERROR)
{
printf("setsockopt(...) err : %d\n", ::GetLastError());
return FALSE;
} return TRUE;
} BOOL CDNSLookup::UnInit()
{
WSACleanup(); return TRUE;
} BOOL CDNSLookup::DNSLookupCore(ULONG ulDNSServerIP, char *szDomainName,
std::vector<ULONG> *pveculIPList, std::vector<std::string> *pvecstrCNameList, ULONG ulTimeout, ULONG *pulTimeSpent)
{
if (m_bIsInitOK == FALSE || szDomainName == NULL)
{
return FALSE;
} //配置SOCKET
sockaddr_in addrDnsServer;
addrDnsServer.sin_family = AF_INET;
addrDnsServer.sin_addr.s_addr = ulDNSServerIP;
addrDnsServer.sin_port = htons(DNS_PORT); //DNS查询与解析
if (!SendDNSRequest(addrDnsServer, szDomainName))
{
return FALSE;
} if (!RecvDNSResponse(addrDnsServer, ulTimeout, pveculIPList, pvecstrCNameList, pulTimeSpent))
{
return FALSE;
} return TRUE;
} BOOL CDNSLookup::SendDNSRequest(sockaddr_in _addrDnsServer, char *_szDomainName)
{
char bufSend[DNS_PACKET_MAX_SIZE] = {};
char* pcSend = &bufSend[]; //填充DNS查询报文头部
DNSHeader *pDnsHdr = (DNSHeader*)pcSend;
pDnsHdr->usTransID = (USHORT)GetCurrentProcessId();
pDnsHdr->usFlags = htons(0x0100);
pDnsHdr->usQuestionCount = htons(0x0001);
pDnsHdr->usAnswerCount = 0x0000;
pDnsHdr->usAuthorityCount = 0x0000;
pDnsHdr->usAdditionalCount = 0x0000; //设置DNS查询报文内容
USHORT usQType = htons(0x0001);
USHORT usQClass = htons(0x0001);
USHORT nDomainNameLen = strlen(_szDomainName);
char *szEncodedDomainName = (char *)malloc(nDomainNameLen + );
if (szEncodedDomainName == NULL)
{
return FALSE;
}
if (!EncodeDotStr(_szDomainName, szEncodedDomainName, nDomainNameLen + ))
{
return FALSE;
} //填充DNS查询报文内容
USHORT nEncodedDomainNameLen = strlen(szEncodedDomainName) + ;
memcpy(pcSend += sizeof(DNSHeader), szEncodedDomainName, nEncodedDomainNameLen);
memcpy(pcSend += nEncodedDomainNameLen, (char*)(&usQType), DNS_TYPE_SIZE);
memcpy(pcSend += DNS_TYPE_SIZE, (char*)(&usQClass), DNS_CLASS_SIZE);
free(szEncodedDomainName); //发送DNS查询报文
USHORT nDNSPacketSize = sizeof(DNSHeader) + nEncodedDomainNameLen + DNS_TYPE_SIZE + DNS_CLASS_SIZE;
if (sendto(m_sock, bufSend, nDNSPacketSize, , (sockaddr*)&_addrDnsServer, sizeof(_addrDnsServer)) == SOCKET_ERROR)
{
return FALSE;
} return TRUE;
} BOOL CDNSLookup::RecvDNSResponse(sockaddr_in _addrDnsServer, ULONG ulTimeout,
std::vector<ULONG> *pveculIPList, std::vector<std::string> *pvecstrCNameList, ULONG *pulTimeSpent)
{
if (pveculIPList != NULL)
pveculIPList->clear();
if (pvecstrCNameList != NULL)
pvecstrCNameList->clear(); char bufRecv[] = { };
char szDotName[] = { };
USHORT nEncodedNameLen = ;
int iAddrDnsServer = sizeof(_addrDnsServer); DWORD dw1 = ::GetTickCount(); //接收响应报文
if (recvfrom(m_sock, bufRecv, sizeof(bufRecv), , (struct sockaddr*)&_addrDnsServer, &iAddrDnsServer) == SOCKET_ERROR)
{
//WSAETIMEDOUT
printf("DNS recvfrom(...) failed : %d\n", ::GetLastError());
return FALSE;
} DNSHeader *pDnsHdr = (DNSHeader*)bufRecv;
USHORT usQuestionCount = ;
USHORT usAnswerCount = ; if (pDnsHdr->usTransID == (USHORT)GetCurrentProcessId()
&& (ntohs(pDnsHdr->usFlags) & 0xfb7f) == 0x8100 //RFC1035 4.1.1(Header section format)
&& (usQuestionCount = ntohs(pDnsHdr->usQuestionCount)) >=
&& (usAnswerCount = ntohs(pDnsHdr->usAnswerCount)) > )
{
char *pDNSData = bufRecv + sizeof(DNSHeader); //解析Question字段
for (int q = ; q != usQuestionCount; ++q)
{
if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, sizeof(szDotName)))
{
return FALSE;
}
pDNSData += (nEncodedNameLen + DNS_TYPE_SIZE + DNS_CLASS_SIZE);
} //解析Answer字段
for (int a = ; a != usAnswerCount; ++a)
{
if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, sizeof(szDotName), bufRecv))
{
return FALSE;
}
pDNSData += nEncodedNameLen; USHORT usAnswerType = ntohs(*(USHORT*)(pDNSData));
USHORT usAnswerClass = ntohs(*(USHORT*)(pDNSData + DNS_TYPE_SIZE));
ULONG usAnswerTTL = ntohl(*(ULONG*)(pDNSData + DNS_TYPE_SIZE + DNS_CLASS_SIZE));
USHORT usAnswerDataLen = ntohs(*(USHORT*)(pDNSData + DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE));
pDNSData += (DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE + DNS_DATALEN_SIZE); if (usAnswerType == DNS_TYPE_A && pveculIPList != NULL)
{
ULONG ulIP = *(ULONG*)(pDNSData);
pveculIPList->push_back(ulIP);
}
else if (usAnswerType == DNS_TYPE_CNAME && pvecstrCNameList != NULL)
{
if (!DecodeDotStr(pDNSData, &nEncodedNameLen, szDotName, sizeof(szDotName), bufRecv))
{
return FALSE;
}
pvecstrCNameList->push_back(szDotName);
} pDNSData += (usAnswerDataLen);
} } DWORD dw2 = ::GetTickCount();
if (pulTimeSpent != NULL)
*pulTimeSpent = dw2 - dw1; return TRUE;
} /*
* convert "www.baidu.com" to "\x03www\x05baidu\x03com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
*/
BOOL CDNSLookup::EncodeDotStr(char *szDotStr, char *szEncodedStr, USHORT nEncodedStrSize)
{
USHORT nDotStrLen = strlen(szDotStr); if (szDotStr == NULL || szEncodedStr == NULL || nEncodedStrSize < nDotStrLen + )
{
return FALSE;
} char *szDotStrCopy = new char[nDotStrLen + ];
//strcpy_s(szDotStrCopy, nDotStrLen + 1, szDotStr);
strcpy(szDotStrCopy, szDotStr); char *pNextToken = NULL;
//char *pLabel = strtok_s(szDotStrCopy, ".", &pNextToken);
char *pLabel = strtok(szDotStrCopy, ".");
USHORT nLabelLen = ;
USHORT nEncodedStrLen = ;
while (pLabel != NULL)
{
if ((nLabelLen = strlen(pLabel)) != )
{
//sprintf_s(szEncodedStr + nEncodedStrLen, nEncodedStrSize - nEncodedStrLen, "%c%s", nLabelLen, pLabel);
sprintf(szEncodedStr + nEncodedStrLen, "%c%s", nLabelLen, pLabel);
nEncodedStrLen += (nLabelLen + );
}
//pLabel = strtok_s(NULL, ".", &pNextToken);
pLabel = strtok(NULL, ".");
} delete[] szDotStrCopy; return TRUE;
} /*
* convert "\x03www\x05baidu\x03com\x00" to "www.baidu.com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
* convert "\x03www\x05baidu\xc0\x13" to "www.baidu.com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 c0 13 ff ff ff ff
* 0x0010 ff ff ff 03 63 6f 6d 00 ff ff ff ff ff ff ff ff
*/
BOOL CDNSLookup::DecodeDotStr(char *szEncodedStr, USHORT *pusEncodedStrLen, char *szDotStr, USHORT nDotStrSize, char *szPacketStartPos)
{
if (szEncodedStr == NULL || pusEncodedStrLen == NULL || szDotStr == NULL)
{
return FALSE;
} char *pDecodePos = szEncodedStr;
USHORT usPlainStrLen = ;
BYTE nLabelDataLen = ;
*pusEncodedStrLen = ; while ((nLabelDataLen = *pDecodePos) != 0x00)
{
if ((nLabelDataLen & 0xc0) == ) //普通格式,LabelDataLen + Label
{
if (usPlainStrLen + nLabelDataLen + > nDotStrSize)
{
return FALSE;
}
memcpy(szDotStr + usPlainStrLen, pDecodePos + , nLabelDataLen);
memcpy(szDotStr + usPlainStrLen + nLabelDataLen, ".", );
pDecodePos += (nLabelDataLen + );
usPlainStrLen += (nLabelDataLen + );
*pusEncodedStrLen += (nLabelDataLen + );
}
else //消息压缩格式,11000000 00000000,两个字节,前2位为跳转标志,后14位为跳转的偏移
{
if (szPacketStartPos == NULL)
{
return FALSE;
}
USHORT usJumpPos = ntohs(*(USHORT*)(pDecodePos)) & 0x3fff;
USHORT nEncodeStrLen = ;
if (!DecodeDotStr(szPacketStartPos + usJumpPos, &nEncodeStrLen, szDotStr + usPlainStrLen, nDotStrSize - usPlainStrLen, szPacketStartPos))
{
return FALSE;
}
else
{
*pusEncodedStrLen += ;
return TRUE;
}
}
} szDotStr[usPlainStrLen - ] = '\0';
*pusEncodedStrLen += ; return TRUE;
}
(3)main.cpp
#include <iostream>//#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h>
#include "CDNSLookup.h" int main(void)
{
//char szDomainName[] = "www.baidu.com";
char szDomainName[] = "hopeex.com";
std::vector<ULONG> veculIPList;
std::vector<std::string> vecstrIPList;
std::vector<std::string> vecCNameList;
ULONG ulTimeSpent = ;
CDNSLookup dnslookup;
BOOL bRet = dnslookup.DNSLookup(inet_addr("114.114.114.114"), szDomainName, &vecstrIPList, &vecCNameList, , &ulTimeSpent);
//BOOL bRet = dnslookup.DNSLookup(inet_addr("221.228.255.1"), szDomainName, &vecstrIPList, &vecCNameList, 1000, &ulTimeSpent); printf("DNSLookup result (%s):\n", szDomainName);
if (!bRet)
{
printf("timeout!\n");
return -;
} for (int i = ; i != veculIPList.size(); ++i)
{
printf("IP%d(ULONG) = %u\n", i + , veculIPList[i]);
}
for (int i = ; i != vecstrIPList.size(); ++i)
{
printf("IP%d(string) = %s\n", i + , vecstrIPList[i].c_str());
}
for (int i = ; i != vecCNameList.size(); ++i)
{
printf("CName%d = %s\n", i + , vecCNameList[i].c_str());
}
printf("time spent = %ums\n", ulTimeSpent); return ;
}
2.2、只解析IPv4地址的精简版代码
(1)dms_z.h
#pragma once // C++实现DNS域名解析 - Snser - 博客园.html (https://www.cnblogs.com/snser/p/4101729.html) #define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS //这里需要导入库 Ws2_32.lib,在不同的IDE下可能不太一样
//#pragma comment(lib, "Ws2_32.lib") #include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib") //#include <windows.h>
#include <string>
#include <vector> #define MAX_DOMAINNAME_LEN 255
#define DNS_PORT 53
#define DNS_TYPE_SIZE 2
#define DNS_CLASS_SIZE 2
#define DNS_TTL_SIZE 4
#define DNS_DATALEN_SIZE 2
#define DNS_TYPE_A 0x0001 //1 a host address
#define DNS_TYPE_CNAME 0x0005 //5 the canonical name for an alias
#define DNS_PACKET_MAX_SIZE (sizeof(DnsHeader) + MAX_DOMAINNAME_LEN + DNS_TYPE_SIZE + DNS_CLASS_SIZE) struct DnsHeader
{
USHORT usTransID; //标识符
USHORT usFlags; //各种标志位
USHORT usQuestionCount; //Question字段个数
USHORT usAnswerCount; //Answer字段个数
USHORT usAuthorityCount; //Authority字段个数
USHORT usAdditionalCount; //Additional字段个数
}; class DnsLookup
{
public:
DnsLookup();
~DnsLookup(); ULONG LookupIPv4(const char* pcDnsServerIP, char *szDomainName,
ULONG ulTimeout = * ); private:
BOOL Init();
BOOL UnInit(); BOOL LookupCore(ULONG ulDNSServerIP, char *szDomainName,
std::vector<ULONG> *pveculIP, ULONG ulTimeOut, ULONG *pulTimeSpent); BOOL SendDNSRequest(sockaddr_in sockAddrDNSServer, char *szDomainName);
BOOL RecvDNSResponse(sockaddr_in sockAddrDNSServer,
std::vector<ULONG> *pveculIP, ULONG ulTimeOut, ULONG *pulTimeSpent); BOOL EncodeDotStr(char *szDotStr, char *szEncodedStr, USHORT nEncodedStrSize);
BOOL DecodeDotStr(char *szEncodedStr, USHORT *pusEncodedStrLen, char *szDotStr, USHORT nDotStrSize, char *szPacketStartPos = NULL); private:
BOOL m_bIsInitOK;
SOCKET m_sock;
};
(2)dns_z.cpp
#include "dns_z.h"
#include <stdio.h>
#include <string.h> DnsLookup::DnsLookup() :
m_bIsInitOK(FALSE),
m_sock(INVALID_SOCKET)
{
m_bIsInitOK = Init();
} DnsLookup::~DnsLookup()
{
UnInit();
} ULONG DnsLookup::LookupIPv4(const char* pcDnsServerIP, char *szDomainName,
ULONG ulTimeout)
{
std::vector<ULONG> veculIP;
ULONG ulTimeSpent;
if (LookupCore(inet_addr(pcDnsServerIP), szDomainName, &veculIP, ulTimeout, &ulTimeSpent))
{
if (veculIP.size() > )
return veculIP.front();
}
return ;
} BOOL DnsLookup::Init()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(, ), &wsaData) == SOCKET_ERROR)
{
printf("WSAStartup(...) err : %d\n", ::GetLastError());
return FALSE;
} if ((m_sock = socket(AF_INET, SOCK_DGRAM, )) == INVALID_SOCKET)
{
printf("socket(...) err : %d\n", ::GetLastError());
return FALSE;
} return TRUE;
} BOOL DnsLookup::UnInit()
{
WSACleanup(); return TRUE;
} BOOL DnsLookup::LookupCore(ULONG ulDNSServerIP, char *szDomainName,
std::vector<ULONG> *pveculIP, ULONG ulTimeOut, ULONG *pulTimeSpent)
{
if (m_bIsInitOK == FALSE || szDomainName == NULL)
return FALSE; //配置SOCKET
sockaddr_in addrDnsServer;
addrDnsServer.sin_family = AF_INET;
addrDnsServer.sin_addr.s_addr = ulDNSServerIP;
addrDnsServer.sin_port = htons(DNS_PORT); //DNS查询与解析
if (!SendDNSRequest(addrDnsServer, szDomainName))
return FALSE;
if (!RecvDNSResponse(addrDnsServer, pveculIP, ulTimeOut, pulTimeSpent))
return FALSE; return TRUE;
} BOOL DnsLookup::SendDNSRequest(sockaddr_in _addrDnsServer, char *_szDomainName)
{
char bufSend[DNS_PACKET_MAX_SIZE] = { };
char* pcSend = &bufSend[]; //填充DNS查询报文头部
DnsHeader *pDnsHdr = (DnsHeader*)pcSend;
pDnsHdr->usTransID = (USHORT)GetCurrentProcessId();
pDnsHdr->usFlags = htons(0x0100);
pDnsHdr->usQuestionCount = htons(0x0001);
pDnsHdr->usAnswerCount = 0x0000;
pDnsHdr->usAuthorityCount = 0x0000;
pDnsHdr->usAdditionalCount = 0x0000; //设置DNS查询报文内容
USHORT usQType = htons(0x0001);
USHORT usQClass = htons(0x0001);
USHORT nDomainNameLen = strlen(_szDomainName);
char *szEncodedDomainName = (char *)malloc(nDomainNameLen + );
if (szEncodedDomainName == NULL)
{
return FALSE;
}
if (!EncodeDotStr(_szDomainName, szEncodedDomainName, nDomainNameLen + ))
{
return FALSE;
} //填充DNS查询报文内容
USHORT nEncodedDomainNameLen = strlen(szEncodedDomainName) + ;
memcpy(pcSend += sizeof(DnsHeader), szEncodedDomainName, nEncodedDomainNameLen);
memcpy(pcSend += nEncodedDomainNameLen, (char*)(&usQType), DNS_TYPE_SIZE);
memcpy(pcSend += DNS_TYPE_SIZE, (char*)(&usQClass), DNS_CLASS_SIZE);
free(szEncodedDomainName); //发送DNS查询报文
USHORT nDNSPacketSize = sizeof(DnsHeader) + nEncodedDomainNameLen + DNS_TYPE_SIZE + DNS_CLASS_SIZE;
if (sendto(m_sock, bufSend, nDNSPacketSize, , (sockaddr*)&_addrDnsServer, sizeof(_addrDnsServer)) == SOCKET_ERROR)
{
return FALSE;
} return TRUE;
} BOOL DnsLookup::RecvDNSResponse(sockaddr_in _addrDnsServer,
std::vector<ULONG> *_pveculIP, ULONG _ulTimeOut, ULONG *_pulTimeSpent)
{
if (_pveculIP != NULL)
_pveculIP->clear(); if (setsockopt(m_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&_ulTimeOut, sizeof(_ulTimeOut)) == SOCKET_ERROR)
{
printf("setsockopt(...) err : %d\n", ::GetLastError());
return FALSE;
} char bufRecv[] = { };
char szDotName[] = { };
USHORT nEncodedNameLen = ;
int iAddrDnsServer = sizeof(_addrDnsServer); DWORD dw1 = ::GetTickCount(); //接收响应报文
if (recvfrom(m_sock, bufRecv, sizeof(bufRecv), , (struct sockaddr*)&_addrDnsServer, &iAddrDnsServer) == SOCKET_ERROR)
{
//WSAETIMEDOUT
printf("DNS recvfrom(...) failed : %d\n", ::GetLastError());
return FALSE;
} DnsHeader *pDnsHdr = (DnsHeader*)bufRecv;
USHORT usQuestionCount = ;
USHORT usAnswerCount = ; if (pDnsHdr->usTransID == (USHORT)GetCurrentProcessId()
&& (ntohs(pDnsHdr->usFlags) & 0xfb7f) == 0x8100 //RFC1035 4.1.1(Header section format)
&& (usQuestionCount = ntohs(pDnsHdr->usQuestionCount)) >=
&& (usAnswerCount = ntohs(pDnsHdr->usAnswerCount)) > )
{
char *pDnsData = bufRecv + sizeof(DnsHeader); //解析Question字段
for (int q = ; q != usQuestionCount; ++q)
{
if (!DecodeDotStr(pDnsData, &nEncodedNameLen, szDotName, sizeof(szDotName)))
{
return FALSE;
}
pDnsData += (nEncodedNameLen + DNS_TYPE_SIZE + DNS_CLASS_SIZE);
} //解析Answer字段
for (int a = ; a != usAnswerCount; ++a)
{
if (!DecodeDotStr(pDnsData, &nEncodedNameLen, szDotName, sizeof(szDotName), bufRecv))
{
return FALSE;
}
pDnsData += nEncodedNameLen; USHORT usAnswerType = ntohs(*(USHORT*)(pDnsData));
USHORT usAnswerClass = ntohs(*(USHORT*)(pDnsData + DNS_TYPE_SIZE));
ULONG usAnswerTTL = ntohl(*(ULONG*)(pDnsData + DNS_TYPE_SIZE + DNS_CLASS_SIZE));
USHORT usAnswerDataLen = ntohs(*(USHORT*)(pDnsData + DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE));
pDnsData += (DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE + DNS_DATALEN_SIZE); if (usAnswerType == DNS_TYPE_A && _pveculIP != NULL)
{
ULONG ulIP = *(ULONG*)(pDnsData);
_pveculIP->push_back(ulIP);
} pDnsData += (usAnswerDataLen);
} } DWORD dw2 = ::GetTickCount();
if (_pulTimeSpent != NULL)
*_pulTimeSpent = dw2 - dw1; return TRUE;
} /*
* convert "www.baidu.com" to "\x03www\x05baidu\x03com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
*/
BOOL DnsLookup::EncodeDotStr(char *szDotStr, char *szEncodedStr, USHORT nEncodedStrSize)
{
USHORT nDotStrLen = strlen(szDotStr); if (szDotStr == NULL || szEncodedStr == NULL || nEncodedStrSize < nDotStrLen + )
{
return FALSE;
} char *szDotStrCopy = new char[nDotStrLen + ];
//strcpy_s(szDotStrCopy, nDotStrLen + 1, szDotStr);
strcpy(szDotStrCopy, szDotStr); char *pNextToken = NULL;
//char *pLabel = strtok_s(szDotStrCopy, ".", &pNextToken);
char *pLabel = strtok(szDotStrCopy, ".");
USHORT nLabelLen = ;
USHORT nEncodedStrLen = ;
while (pLabel != NULL)
{
if ((nLabelLen = strlen(pLabel)) != )
{
//sprintf_s(szEncodedStr + nEncodedStrLen, nEncodedStrSize - nEncodedStrLen, "%c%s", nLabelLen, pLabel);
sprintf(szEncodedStr + nEncodedStrLen, "%c%s", nLabelLen, pLabel);
nEncodedStrLen += (nLabelLen + );
}
//pLabel = strtok_s(NULL, ".", &pNextToken);
pLabel = strtok(NULL, ".");
} delete[] szDotStrCopy; return TRUE;
} /*
* convert "\x03www\x05baidu\x03com\x00" to "www.baidu.com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 03 63 6f 6d 00 ff
* convert "\x03www\x05baidu\xc0\x13" to "www.baidu.com"
* 0x0000 03 77 77 77 05 62 61 69 64 75 c0 13 ff ff ff ff
* 0x0010 ff ff ff 03 63 6f 6d 00 ff ff ff ff ff ff ff ff
*/
BOOL DnsLookup::DecodeDotStr(char *szEncodedStr, USHORT *pusEncodedStrLen, char *szDotStr, USHORT nDotStrSize, char *szPacketStartPos)
{
if (szEncodedStr == NULL || pusEncodedStrLen == NULL || szDotStr == NULL)
{
return FALSE;
} char *pDecodePos = szEncodedStr;
USHORT usPlainStrLen = ;
BYTE nLabelDataLen = ;
*pusEncodedStrLen = ; while ((nLabelDataLen = *pDecodePos) != 0x00)
{
if ((nLabelDataLen & 0xc0) == ) //普通格式,LabelDataLen + Label
{
if (usPlainStrLen + nLabelDataLen + > nDotStrSize)
{
return FALSE;
}
memcpy(szDotStr + usPlainStrLen, pDecodePos + , nLabelDataLen);
memcpy(szDotStr + usPlainStrLen + nLabelDataLen, ".", );
pDecodePos += (nLabelDataLen + );
usPlainStrLen += (nLabelDataLen + );
*pusEncodedStrLen += (nLabelDataLen + );
}
else //消息压缩格式,11000000 00000000,两个字节,前2位为跳转标志,后14位为跳转的偏移
{
if (szPacketStartPos == NULL)
{
return FALSE;
}
USHORT usJumpPos = ntohs(*(USHORT*)(pDecodePos)) & 0x3fff;
USHORT nEncodeStrLen = ;
if (!DecodeDotStr(szPacketStartPos + usJumpPos, &nEncodeStrLen, szDotStr + usPlainStrLen, nDotStrSize - usPlainStrLen, szPacketStartPos))
{
return FALSE;
}
else
{
*pusEncodedStrLen += ;
return TRUE;
}
}
} szDotStr[usPlainStrLen - ] = '\0';
*pusEncodedStrLen += ; return TRUE;
}
(3)main.cpp
//#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h>
#include "dns_z.h" int main(void)
{
//char szDomainName[] = "www.baidu.com";
char szDomainName[] = "hopeex.com";
DnsLookup dnslookup;
ULONG ul = dnslookup.LookupIPv4("114.114.114.114", szDomainName, );
//BOOL bRet = dnslookup.DNSLookup(inet_addr("221.228.255.1"), szDomainName, &vecstrIPList, &vecCNameList, 1000, &ulTimeSpent); in_addr* pAddr = (in_addr*)&ul;
printf("%s\n", inet_ntoa(*pAddr)); return ;
}
3、
4、
5、
VC.DNS解析(winsock)的更多相关文章
- 使用dig查询dns解析
原文地址:使用dig查询dns解析 作者:chenwenming 一般来说linux下查询域名解析有两种选择,nslookup或者dig,而在使用上我觉得dig更加方便顺手. 如果是在debian下的 ...
- 可以Ping通和DNS解析,但打不开网页的解决办法
一. 网络故障表现为: 1.Ping地址正常,能ping通任何本来就可以ping通地址,如网关.域名. 2.能DNS解析域名. 3.无法打开网页,感觉是网页打开的一瞬间就显示无网络连接. 4.只需要连 ...
- 如何获取浏览器的DNS解析时间
上一篇博客提到09年初WED团队开发的浏览器环境检测工具时,忘记说这个是aoao同学的创意了.不过没关系,据说他又在秘密规划新版本了,再据说新版要增加的DNS解析时间计算已经开发完成,点上面那个链接就 ...
- 解决dns服务器未找到问题 &&DNS解析服务器&&连接问题
第一部分: 有时已经连接到了网络,但是却提示未找到dns服务器,或未连接dns服务器,这多是因为dns设置的问题.下面是几种可行的解决方法. 方法一: 1. win + R -> cmd - ...
- DNS解析过程详解
先说一下DNS的几个基本概念: 一. 根域 就是所谓的“.”,其实我们的网址www.baidu.com在配置当中应该是www.baidu.com.(最后有一点),一般我们在浏览器里输入时会省略后面的点 ...
- C#实现DNS解析服务和智能DNS服务
C#实现DNS解析服务有一个开源项目ARSoft.Tools.Net, ARSoft.Tools.Net是一个非常强大的开源DNS控件库,包含.Net SPF validation, SenderID ...
- 解决域名DNS解析的故障
在实际应用过程中可能会遇到DNS解析错误的问题,就是说当我们访问一个域名时无法完成将其解析到IP地址的工作,而直接输入网站IP却可以正常访问,这就是因为DNS解析出现故障造成的.这个现象发生的机率比较 ...
- LINUX DNS解析的3种修改方法~
1.HOST 本地DNS解析 vi /etc/hosts 添加规则 例如: 223.231.234.33 www.baidu.com 2.网卡配置文件DNS服务地址 vi /etc/sysconfi ...
- DNS解析过程和域名收敛、域名发散、SPDY应用
前段时间项目要做域名收敛,糊里糊涂的完成了,好多原理不清晰,现在整理搜集下知识点. 域名收敛的目的是什么?简单来说就是域名解析慢.那为什么解析慢?且听下文慢慢道来. 什么是DNS? DNS( Doma ...
随机推荐
- 正确使用Java读写锁
JDK8中引入了高性能的读写锁StampedLock,它的核心思想在于,在读的时候如果发生了写,应该通过重试的方式来获取新的值,而不应该阻塞写操作.这种模式也就是典型的无锁编程思想,和CAS自旋的思想 ...
- 《挑战30天C++入门极限》C++中类的多态与虚函数的使用
C++中类的多态与虚函数的使用 类的多态特性是支持面向对象的语言最主要的特性,有过非面向对象语言开发经历的人,通常对这一章节的内容会觉得不习惯,因为很多人错误的认为,支持类的封装的语言就是支持 ...
- 解决tecplot中壁面速度不为0的问题
当直接将fluent的.cas文件和.dat文件导入tecplot中进行后处理的时候,我们会发现,壁面速度不为0的情况(见上图). 出现这样问题的原因为:fluent的计算数据是存储在每个单元的中心位 ...
- UMD、CommonJS、ES Module、AMD、CMD模块的写法
AMD异步模块规范 RequireJS就是AMD的一个典型的实现. 以下是一个只依赖与jQuery的模块代码: // foo.js define(['jquery'], function($){ // ...
- redis 业务锁 not exist 模式
背景: 业务核心模块只能提交一次,原实现方案 前端加提交限制.后端加数据库业务逻辑判定,结果失效,api站点部署多台负载,切方法需要强求第三方接口 响应时间较慢 ,故放弃lock. 解决方案:redi ...
- [转]MyEclipse基础学习:Java EE Learning Center
我就不翻译了,直接给出Java EE学习中心的原文链接: Java EE Learning Center 另外,给出MyEclipse IDE 环境中Apache Tomcat server服务器正常 ...
- python blob操作
最近在学习使用Python,操作Oracle数据库采用的是cx_Oracle模块. 对于基本字段,都可以正常操作.但是对于Blob字段,我试试好几次,都没成功.下面贴出测试代码,与大家讨论讨论. 这是 ...
- python 设计模式之单例模式 Singleton Pattern
#引入 一个类被设计出来,就意味着它具有某种行为(方法),属性(成员变量).一般情况下,当我们想使用这个类时,会使用new 关键字,这时候jvm会帮我们构造一个该类的实例.这么做会比较耗费资源. 如果 ...
- Java 读取clob字段的几种方法
Java 读取clob字段的几种方法 一.第一种 Clob clob = rs.getClob("remark");//Java.sql.Clob String detailinf ...
- layui 鼠标悬停单元格显示全部
{field : 'subjectId',title : '主题id',align: 'center',edit : 'text',templet:'<div><span title ...