c - C 代码从 CentOS 迁移到 Windows ^

标签 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 等一些 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.hws2def.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/

相关文章:

c - 存储 malloc 的返回值(空指针)

mysql - 如何在没有数据库的情况下安装 MySQL 客户端(在 Windows 服务器上)

python - 在 Windows 上执行脚本时隐藏控制台

c - 套接字编程 - 序列化

c++ - Linux 中 C++ 的 UDP Socket 编程

c 程序从给定链表中删除元素并在删除后打印整个列表

c - mmap(),内存驻留在虚拟空间的哪里?

php - 使用ffmpeg和php为视频每毫秒添加图像叠加层

ruby-on-rails - 套接字错误 : HiPay Integration in Rails app (Payment API)

c - 下面的代码有什么作用?