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 ...
随机推荐
- cube.js 学习(四)cube.js cube 说明
cube 是cube.js data schema 的核心,里面定义了生成sql 的说明 一个比较全的schema 例子 cube(`Users`, { sql: `select * from u ...
- Dart 日期时间 DateTime
1.获取当前时间 var now = new DateTime.now(); print(now); // 2019-06-20 16:59:05.560543 2.设置时间 var d =new D ...
- sed 替换文件内容
方法1:sed -i 's/被替换的内容/要替换成的内容/' file 方法2:sed 's/被替换的内容/要替换成的内容/g' file > file.out:mv file.out file ...
- NAT+PAT+OSPF+设备互连地址详解
- 【JVM】虚拟机字节码执行引擎
概念模型上,典型的帧栈结构如下(栈是线程私有的,也就是每个线程都会有自己的栈). 典型的帧栈结构 局部变量表 存放方法参数和方法内部定义的局部变量.在编译阶段, ...
- git 删除文件 、只删除远程仓库文件、更换远程仓库
一.删除文件 1.克隆远程仓库到本地库. 例如使用ssh方法: git clone git@github.com:xxx/xxx.git 2.对需要删除的文件.文件夹进行如下操作: git rm te ...
- 深入理解JS中&&和||
写了这么多JS,才发现JS的语法既是属于C语系的,又与一般C语系的编程语言某些地方有很大区别,其中&&和||就是其中一例. C语系中的&&和|| C语系的&&a ...
- Python脚本基础运算和算法
原文地址:https://www.cnblogs.com/ailiailan/p/10141741.html 通过关注“常见”脚本,是对代码的一个很好的学习和总结的方式. 1.冒泡排序 lis = [ ...
- linux命令实现音频格式转换和拼接
安装FFmpeg flaceric@ray:~$ sudo apt install FFmpeg flac 安装lame faaceric@ray:~$ sudo apt install lame f ...
- 在mac中安装tmux
在mac 中安装Tmux: 在终端输入如下命令: brew install tmux Tmux 的快捷键前缀(Prefix) 为了使自身的快捷键和其他软件的快捷键互不干扰,Tmux 提供了一个快捷键 ...