这是我的代码的一部分。
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 等一些 header 更改为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
window ?
我在windows7上用mingw+msys编译的。
我按照@selbie所说添加
#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
最佳答案
您缺少#include。在源文件顶部(或预编译文件顶部)包含 winsock2.h
后,包含 ws2tcpip.h
或 ws2def.h
头文件)。
#include <WinSock2.h>
#include <WS2tcpip.h>
然后链接到ws2_32.lib。
当你的程序开始初始化winsock时,不要忘记调用WSAStartup:
WSAData data;
WSAStartup(MAKEWORD(2,2), &data);
关于c - C 代码从 CentOS 迁移到 Windows ^,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21930204/