DNS Sample Code
This page demonstrates how to perform DNS queries using the Windows DnsQuery API in C++. The sample includes both IPv4 and IPv6 lookups, error handling, and resource cleanup.
Prerequisites
- Windows 10 SDK or later
- Visual Studio 2019+ (or any compiler that supports the Windows SDK)
- Administrator privileges (optional, for certain DNS record types)
Sample Code (C++)
#include <windows.h>
#include <winldap.h>
#include <windns.h>
#include <iostream>
#include <vector>
#include <string>
#pragma comment(lib, "dnsapi.lib")
void PrintDnsRecord(PDNS_RECORD record) {
while (record) {
std::wcout << L"Record Type: " << record->wType << L"\\n";
if (record->Data.A) {
std::wcout << L"IPv4: " << record->Data.A->IpAddress << L"\\n";
} else if (record->Data.AAAA) {
wchar_t ip[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &record->Data.AAAA->Ip6Address, ip, sizeof(ip));
std::wcout << L"IPv6: " << ip << L"\\n";
} else if (record->Data.PTR) {
std::wcout << L"PTR: " << record->Data.PTR->pNameHost << L"\\n";
}
record = record->pNext;
}
}
int main() {
const wchar_t* hostname = L"example.com";
PDNS_RECORD result = nullptr;
DNS_STATUS status = DnsQuery_W(hostname,
DNS_TYPE_A,
DNS_QUERY_BYPASS_CACHE,
nullptr,
&result,
nullptr);
if (status != 0) {
std::wcerr << L"DnsQuery failed: " << status << L"\\n";
return 1;
}
std::wcout << L"Results for " << hostname << L":\\n";
PrintDnsRecord(result);
DnsRecordListFree(result, DnsFreeRecordList);
return 0;
}
Run the Sample
- Save the code above as
DnsLookup.cpp. - Open a Developer Command Prompt for Visual Studio.
- Compile:
cl /EHsc DnsLookup.cpp /link dnsapi.lib
- Execute:
DnsLookup.exe