在win10环境下直接使用 #include <sys/socket.h> 会报错
时间: 2023-09-16 08:10:00 浏览: 175
是的,因为 `<sys/socket.h>` 是 Unix/Linux 系统下的头文件,无法在 Windows 下直接使用。如果需要在 Windows 下进行 socket 编程,需要使用 Windows 提供的 socket API,其对应的头文件是 `<winsock2.h>`。在使用之前需要调用 `WSAStartup()` 函数进行初始化。以下是一个简单的 Windows 下的 socket 示例代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsa_data;
int ret = WSAStartup(MAKEWORD(2, 2), &wsa_data);
if (ret != 0) {
printf("WSAStartup failed: %d\n", ret);
return -1;
}
// 创建 socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
printf("socket failed: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
// 连接到服务器
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8080);
ret = connect(sock, (SOCKADDR*)&server_addr, sizeof(server_addr));
if (ret == SOCKET_ERROR) {
printf("connect failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
// 发送数据
const char* msg = "Hello, server!";
ret = send(sock, msg, strlen(msg), 0);
if (ret == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
// 接收数据
char buf[1024];
ret = recv(sock, buf, sizeof(buf), 0);
if (ret == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
buf[ret] = '\0';
printf("Received: %s\n", buf);
// 关闭 socket
closesocket(sock);
WSACleanup();
return 0;
}
```
阅读全文