将C代码从CentOS迁移到Windows ^

时间:2014-02-21 09:24:32

标签: c windows sockets centos winsock

这是我的代码的一部分。

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

此代码将在Linux中成功编译,但不会在Windows中编译。

我已将sys / socket.h之类的标题更改为winsock.h。

我收到的消息是。

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;

我该如何修复它们?

例如关于实际^指向提示的第一个错误,如何使用addrinfo结构而不是包含netdb.h用于Windows?

我在windows7上的mingw + msys编译了它。

我添加了@selbie saied

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

然后情况发生了变化。

$ 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

1 个答案:

答案 0 :(得分:1)

你错过了#include。将ws2tcpip.h包含在源文件的顶部(或预编译头文件的顶部)后,请加ws2def.hwinsock2.h

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

然后与ws2_32.lib链接。

当程序开始初始化winsock时,不要忘记调用WSAStartup:

 WSAData data;
 WSAStartup(MAKEWORD(2,2), &data);