Question

This is a part of my code.

int sock;
struct addrinfo hints,*res;
int err;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC; 
hints.ai_socktype = SOCK_DGRAM;
err = getaddrinfo(hostName,portNum,&hints,&res);

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);    
}

This code will be compiled successfully in Linux but won’t be compiled in windows.

I’ve changed some headers like sys/socket.h to winsock.h.

The messages I got is following.

sample.c:32:18: error: storage size of 'hints' isn't known
  struct addrinfo hints,*res;
                  ^
sample.c:48:36: error: dereferencing pointer to incomplete type
  for (rp = res; rp != NULL; rp = rp->ai_next) {
                                    ^
sample.c:51:34: error: dereferencing pointer to incomplete type
   addr = (struct sockaddr_in *)rp->ai_addr;

How can I fix them?

For example about the first error which actually ^ points at hints, how can I use addrinfo structure instead of including netdb.h for windows?

I compiled it at mingw+msys on windows7.

I added as @selbie saied

#include <WinSock2.h>
#include <WS2tcpip.h>

Then situation's changed.

$ gcc -o udpSample.ot udpSample.c
C:\Users\user\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x11e): undefined reference to `getaddrinfo'
C:\Users\user\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x19a): undefined reference to `ntohs@4'
C:\Users\user\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x1be): undefined reference to `inet_ntoa@4'
C:\Users\user\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x1df): undefined reference to `inet_ntoa@4'
C:\Users\user\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x270): undefined reference to `udpServer' <- This is a my app.
C:\Users\Juser\AppData\Local\Temp\ccwFEwZi.o:udpSample.c:(.text+0x2e8): undefined reference to `udpClient' <- This is a my app too.
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe:
 C:\Users\user\AppData\Local\Temp\ccwFEwZi.o: 
 bad reloc address 0x20 in section `.eh_frame'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
Was it helpful?

Solution

You are missing a #include. Include either ws2tcpip.h or ws2def.h after including winsock2.h at the top of your source file (or at the top of your precompiled header file).

#include <WinSock2.h>
#include <WS2tcpip.h>

Then link with ws2_32.lib.

Don't forget to call WSAStartup when your program starts to init winsock:

 WSAData data;
 WSAStartup(MAKEWORD(2,2), &data);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top