首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C89:在Windows上获取getaddrinfo()?

C89:在Windows上获取getaddrinfo()?
EN

Stack Overflow用户
提问于 2010-02-23 10:10:46
回答 1查看 2.8K关注 0票数 3

我是C89的新手,正在尝试做一些套接字编程:

代码语言:javascript
复制
void get(char *url) {
    struct addrinfo *result;
    char *hostname;
    int error;

    hostname = getHostname(url);

    error = getaddrinfo(hostname, NULL, NULL, &result);

}

我是在Windows上开发的。Visual Studio抱怨说,如果我使用以下include语句,则没有这样的文件:

代码语言:javascript
复制
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

我该怎么办?这是否意味着我不能移植到Linux?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-02-23 10:14:28

在Windows上,以下内容应该足够了,而不是您提到的includes:

代码语言:javascript
复制
#include <winsock2.h>
#include <windows.h>

您还必须链接到ws2_32.lib。这样做有点丑陋,但是对于VC++,你可以通过:#pragma comment(lib, "ws2_32.lib")

Winsock和POSIX之间的其他差异包括:

在使用任何套接字之前,你必须先调用

  • ,现在称为传递套接字的closesocket().
  • Instead of
    • as int,有一个等于指针大小的SOCKET。尽管微软有一个名为INVALID_SOCKET的宏来隐藏这一点,但您仍然可以使用与-1的比较来表示错误。
    • 对于设置非阻塞标志之类的事情,您将使用ioctlsocket()而不是fcntl().
    • You'll必须使用send()recv()而不是write()write()

至于如果你开始为Winsock编码,你是否会失去Linux代码的可移植性...如果你不小心,那么是的。但是您可以编写代码,尝试使用#ifdef来弥补这一差距。

例如:

代码语言:javascript
复制
#ifdef _WINDOWS

/* Headers for Windows */
#include <winsock2.h>
#include <windows.h>

#else

/* Headers for POSIX */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

/* Mimic some of the Windows functions and types with the
 * POSIX ones.  This is just an illustrative example; maybe
 * it'd be more elegant to do it some other way, like with
 * a proper abstraction for the non-portable parts. */

typedef int SOCKET;

#define INVALID_SOCKET  ((SOCKET)-1)

/* OK, "inline" is a C99 feature, not C89, but you get the idea... */
static inline int closesocket(int fd) { return close(fd); }
#endif

一旦你做了这样的事情,你就可以针对出现在两个操作系统中的函数进行编码,在适当的地方使用这些包装器。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2315701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档