如何在 Windows 上使用 sys/socket.h?

Mah*_*oud 8 c c++ sockets server

我在 Linux 机器上使用套接字用 C 语言制作了一个服务器,它工作正常,但是当我尝试使用 Visual Studio 在 Windows 机器上运行它时,出现错误:

致命错误 C1083:无法打开包含文件:'sys/socket.h':没有这样的文件或目录

ide 告诉我找不到这个头文件。

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
Run Code Online (Sandbox Code Playgroud)

fpi*_*tte 13

对于 Windows,您必须使用winsock.horwinsock2.hsys/types.h。忘记unistd.h,arpa/inet.hnetinet.h。使用条件编译根据平台包含正确的标头。

另外,要在 Windows 下使用套接字,您的应用程序必须首先调用WSAStartup.

Windows 和 Linux 之间的大部分调用是相同的。但大多数性能都需要避免 select() (它有效)并使用 Windows 函数。请参阅文档