我是C89的新手,正在尝试做一些套接字编程:
void get(char *url) {
struct addrinfo *result;
char *hostname;
int error;
hostname = getHostname(url);
error = getaddrinfo(hostname, NULL, NULL, &result);
}我是在Windows上开发的。Visual Studio抱怨说,如果我使用以下include语句,则没有这样的文件:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>我该怎么办?这是否意味着我不能移植到Linux?
发布于 2010-02-23 10:14:28
在Windows上,以下内容应该足够了,而不是您提到的includes:
#include <winsock2.h>
#include <windows.h>您还必须链接到ws2_32.lib。这样做有点丑陋,但是对于VC++,你可以通过:#pragma comment(lib, "ws2_32.lib")
Winsock和POSIX之间的其他差异包括:
在使用任何套接字之前,你必须先调用
closesocket().int,有一个等于指针大小的SOCKET。尽管微软有一个名为INVALID_SOCKET的宏来隐藏这一点,但您仍然可以使用与-1的比较来表示错误。ioctlsocket()而不是fcntl().send()和recv()而不是write()和write()至于如果你开始为Winsock编码,你是否会失去Linux代码的可移植性...如果你不小心,那么是的。但是您可以编写代码,尝试使用#ifdef来弥补这一差距。
例如:
#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一旦你做了这样的事情,你就可以针对出现在两个操作系统中的函数进行编码,在适当的地方使用这些包装器。
https://stackoverflow.com/questions/2315701
复制相似问题