这个问题在这里已有答案:
我试图在C中执行一个简单的DNS查找。这是我的代码(我主要从一个例子中解释):
#include <winsock2.h>
#include <windns.h>
#include <stdio.h>
char* DNS_Lookup(char* host) {
DNS_STATUS status; //Return value of DnsQuery_A() function.
PDNS_RECORD pDnsRecord; //Pointer to DNS_RECORD structure.
PIP4_ARRAY pSrvList = NULL; //Pointer to IP4_ARRAY structure.
WORD wType; //Type of the record to be queried.
char* pOwnerName = host; //Owner name to be queried.
char pReversedIP[255]; //Reversed IP address.
char DnsServIp[255]; //DNS server ip address.
DNS_FREE_TYPE freetype;
freetype = DnsFreeRecordList;// DnsFreeRecordListDeep;
IN_ADDR ipaddr;
status = DnsQuery(pOwnerName, //Pointer to OwnerName.
wType, //Type of the record to be queried.
DNS_QUERY_BYPASS_CACHE, // Bypasses the resolver cache on the lookup.
pSrvList, //Contains DNS server IP address.
&pDnsRecord, //Resource record that contains the response.
NULL); //Reserved for future use.
if(status) {
printf("Failed to query the host record for %s and the error is %d \n", pOwnerName, status);
} else {
ipaddr.S_un.S_addr = (pDnsRecord->Data.A.IpAddress);
printf("The IP address of the host %s is %s \n", pOwnerName,inet_ntoa(ipaddr));
// Free memory allocated for DNS records.
DnsRecordListFree(pDnsRecord, freetype);
}
LocalFree(pSrvList);
return inet_ntoa(ipaddr);
}
当我尝试编译时,我会收到链接器错误(为了清晰起见,我已经清理了一些错误):
gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -w
c:/<..>/mingw32/bin/ld.exe: <..>/ccRVIgMi.o: in function `Z10DNS_LookupPc':
../dns.c:17: undefined reference to `DnsQuery_A@24'
c:/<..>/mingw32/bin/ld.exe: <..>/dns.c:30: undefined reference to `DnsRecordListFree@8'
collect2.exe: error: ld returned 1 exit status
我知道为了使用winsock2.h
编译代码我必须将-lws2_32
添加到我的gcc命令,我猜我必须做类似的编译代码使用windns.h
,但我一直无法在网上找到任何帮助。
应该是正确的答案
gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -ldnsapi -w
但正如你发现它不起作用。值得庆幸的是,gcc
非常聪明,可以提供一种恢复方式:
gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -ldnsapi.dll -w
如果由于某些原因无效并且您在Windows上编译而不是交叉编译,这将起作用:
gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -lc:\windows\system32\dnsapi.dll -w