【问题标题】:How to use getaddrinfo() on windows如何在 Windows 上使用 getaddrinfo()
【发布时间】:2014-02-25 08:47:22
【问题描述】:

我正在尝试使用 mingw+msys 构建我的 APP。

我的代码使用了 winsock。当我编译它时,我收到以下错误消息:

$ 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

这是我从 Linux 迁移的代码,更改了一些标头。

#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( );                                    

}

如何在 Windows 中使用gettarrinfo()

这是尝试dgreenday的文章后消息更改的附加信息。

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*,

【问题讨论】:

标签: c compilation winsock getaddrinfo


【解决方案1】:

我怀疑您只是拥有一个过时的 SDK,并且您的 SDK 中提供的导入库不包括 getaddrinfo。您的程序在我的 mingw 系统上按照您描述链接的方式编译。

要么更新你的 mingw 系统,要么创建一个包含 getaddrinfo 的导入库。

注意:

getaddrinfo("124.0.0.1",12345,&hints,&res);

应该是:

getaddrinfo("124.0.0.1","12345",&hints,&res);

而且您没有正确检查错误。您必须注意getaddrinfo 返回的值。不适合忽略这一点,然后继续检查errno

【讨论】:

  • 我固定到getaddrinfo("124.0.0.1","12345",&amp;hints,&amp;res); 并且进展顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
相关资源
最近更新 更多