C89:Windows 上的 getaddrinfo() ?
我是 C89 的新手,正在尝试进行一些套接字编程:
void get(char *url) {
struct addrinfo *result;
char *hostname;
int error;
hostname = getHostname(url);
error = getaddrinfo(hostname, NULL, NULL, &result);
}
我正在 Windows 上进行开发。如果我使用这些 include 语句,Visual Studio 会抱怨没有这样的文件:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
我该怎么办?这是否意味着我无法移植到 Linux?
I'm new to C89, and trying to do some socket programming:
void get(char *url) {
struct addrinfo *result;
char *hostname;
int error;
hostname = getHostname(url);
error = getaddrinfo(hostname, NULL, NULL, &result);
}
I am developing on Windows. Visual Studio complains that there is no such file if I use these include statements:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
What should I do? Does this mean that I won't have portability to Linux?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Windows 上,不需要您提到的包含内容,以下内容就足够了:
您还必须链接到
ws2_32.lib
。这样做有点丑陋,但对于 VC++,您可以通过以下方式做到这一点:#pragma comment(lib, "ws2_32.lib")
Winsock 和 POSIX 之间的其他一些区别包括:
您必须调用
WSAStartup()
在使用任何套接字函数之前。
close()
现在称为closesocket()
。不是将套接字作为
int
传递,而是使用一个等于指针大小的 typedefSOCKET
。尽管 Microsoft 有一个名为INVALID_SOCKET
的宏来隐藏此错误,但您仍然可以使用与-1
进行比较。对于设置非阻塞标志之类的操作,您将使用
ioctlsocket()
而不是fcntl()
。您必须使用
send()
和recv()
而不是write()
和read()< /code>.
至于如果您开始为 Winsock 编写代码是否会失去 Linux 代码的可移植性……如果您不小心,那么是的。但是您可以编写尝试使用
#ifdef
来弥补差距的代码。例如:
然后,一旦您执行了类似的操作,您就可以使用这些包装器针对两个操作系统中出现的函数进行编码在适当的情况下。
On Windows, instead of the includes you have mentioned, the following should suffice:
You'll also have to link to
ws2_32.lib
. It's kind of ugly to do it this way, but for VC++ you can do this via:#pragma comment(lib, "ws2_32.lib")
Some other differences between Winsock and POSIX include:
You will have to call
WSAStartup()
before using any socket functions.close()
is now calledclosesocket()
.Instead of passing sockets as
int
, there is a typedefSOCKET
equal to the size of a pointer. You can still use comparisons with-1
for error, though Microsoft has a macro calledINVALID_SOCKET
to hide this.For things like setting non-blocking flags, you'll use
ioctlsocket()
instead offcntl()
.You'll have to use
send()
andrecv()
instead ofwrite()
andread()
.As for whether or not you will lose portability with Linux code if you start coding for Winsock... If you are not careful, then yes. But you can write code that tries to bridge the gaps using
#ifdef
s..For example:
Then once you do something like this, you can code against the functions which appear in both OS's, using these wrappers where appropriate.