C89:Windows上的getaddrinfo()?

Nic*_*ner 3 c sockets windows c89

我是C89的新手,并试图做一些套接字编程:

void get(char *url) {
    struct addrinfo *result;
    char *hostname;
    int error;

    hostname = getHostname(url);

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

}
Run Code Online (Sandbox Code Playgroud)

我在Windows上开发.如果我使用这些include语句,Visual Studio会抱怨没有这样的文件:

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
Run Code Online (Sandbox Code Playgroud)

我该怎么办?这是否意味着我将无法移植到Linux?

asv*_*kau 6

在Windows上,而不是您提到的包含,以下应该足够:

#include <winsock2.h>
#include <windows.h>
Run Code Online (Sandbox Code Playgroud)

你还必须链接到ws2_32.lib.这样做有点难看,但对于VC++,你可以通过以下方式完成:#pragma comment(lib, "ws2_32.lib")

Winsock和POSIX之间的其他一些区别包括:

  • WSAStartup()在使用任何套接字函数之前,您必须调用.

  • close()现在被称为closesocket().

  • 而不是传递套接字int,而是有一个SOCKET等于指针大小的typedef .-1尽管微软有一个名为INVALID_SOCKET隐藏它的宏,你仍然可以使用比较来查找错误.

  • 对于设置非阻塞标志的事情,您将使用ioctlsocket()而不是fcntl().

  • 你必须使用send()recv()不是write()read().

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

例如:

#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
Run Code Online (Sandbox Code Playgroud)

然后,一旦你执行了这样的操作,就可以在适当的情况下使用这些包装器对两个操作系统中出现的函数进行编码.