我试图使用mingw + msys构建我的APP。
我的代码使用winsock。当我编译它时,我收到以下错误消息:
$ gcc -o sample sample.c -lws2_32
C:\Users\user\AppData\Local\Temp\ccsdWlQR.o:sample.c:(.text+0xeb): undefined reference to `getaddrinfo'
collect2.exe: error: ld returned 1 exit status
这是我从Linux迁移的代码,更改了一些标题。
#include <stdio.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
main(int argc,char *argv[])
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
printf("Hello world with winsock");
int sock;
char *hostAddress;
struct addrinfo hints,*res;
int err;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
getaddrinfo("127.0.0.1",12345,&hints,&res);
printf("getaddrinfo %s\n",strerror(errno));
printf("getaddrinfo : %s \n",gai_strerror(err));
struct sockaddr_in *addr;
struct addrinfo *rp;
for (rp = res; rp != NULL; rp = rp->ai_next) {
addr = (struct sockaddr_in *)rp->ai_addr;
printf("dstPort = %d\n",ntohs(addr->sin_port));
printf("dstAddr = %s\n",inet_ntoa((struct in_addr)addr->sin_addr));
hostAddress = inet_ntoa((struct in_addr)addr->sin_addr);
}
WSACleanup( );
}
如何在Windows中使用gettarrinfo()
?
这是在尝试dgreenday的文章后更改邮件的其他信息。
sample.c:22:2: warning: passing argument 2 of 'getaddrinfo' makes pointer from i
nteger without a cast [enabled by default]
getaddrinfo("124.0.0.1",12345,&hints,&res);
^
In file included from sample.c:4:0:
c:\mingw\include\ws2tcpip.h:391:12: note: expected 'const char *' but argument i
s of type 'int'
int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
答案 0 :(得分:2)
我怀疑您只是拥有过时的SDK,而SDK中提供的导入库不包含getaddrinfo
。你的程序编译方式就是你在我的mingw系统上描述链接的方式。
更新您的mingw系统,或创建包含getaddrinfo
的导入库。
请注意:
getaddrinfo("124.0.0.1",12345,&hints,&res);
应该是:
getaddrinfo("124.0.0.1","12345",&hints,&res);
并且您没有正确检查错误。您必须注意getaddrinfo
返回的值。忽略它然后继续检查errno
。