I'm trying to build my APP with mingw+msys.
My code usee winsock. When I compile it I take following error message:
$ 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
This is my code that is migrated from Linux with changing some headers.
#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( );
}
How can I use gettarrinfo()
in Windows?
This is the additional information that message is changed after trying dgreenday's article.
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*,
I suspect that you simply have an out of date SDK, and the import library supplied in your SDK does not include getaddrinfo
. Your program, compiled the way you describe links fine on my mingw system.
Either update your mingw system, or create an import library that does contain getaddrinfo
.
Note that:
getaddrinfo("124.0.0.1",12345,&hints,&res);
should be:
getaddrinfo("124.0.0.1","12345",&hints,&res);
And you are not checking for errors correctly. You must take notice of the value returned by getaddrinfo
. It is not appropriate to ignore that and then go on to check errno
.