【发布时间】:2021-10-19 10:54:55
【问题描述】:
我正在尝试在 windows 上的 codelite 中编写一个简单的套接字代码,但我无法导入 ws2_32.h,所以我的项目无法正常工作,我得到“没有这样的文件或目录”。我该如何解决这个问题。我试图在链接器选项中写这个,但我无法成功。我研究了这样的问题,但我无法理解。这是 Codelite 的新版本,与其他版本不同。我使用 MinGW 作为编译器。
编辑: 我删除了一个不必要且错误的库(#include“ws2_32.h”),当我将“-Iws2_32”添加到链接器选项时,问题就解决了。
#define _WINSOCK_DEPRECATED_NO_WARNINGS
//#ifndef WIN32_LEAN_AND_MEAN
//#define WIN32_LEAN_AND_MEAN
//#endif
#include <stdio.h>
#include <string.h>
#include "winsock2.h"
#include "ws2_32.h"
#include <WS2tcpip.h>
#define SERVER_BUF 10
#define SAME 0
#define G_BUF 1024
int main()
{
WSADATA wsa=NULL;
SOCKET s, new_socket;
char buf[SERVER_BUF];
char gbuf[G_BUF];
struct sockaddr_in server_information;
struct sockaddr_in client_information;
WSAStartup(MAKEWORD(2, 2), &wsa);
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
server_information.sin_family = AF_INET;
server_information.sin_addr.s_addr = inet_addr("192.168.10.16");
server_information.sin_port = htons(8888);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s != -1)
{
printf("Soket created...");
}
if (bind(s, (struct sockaddr*)&server_information, sizeof(server_information)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
}
puts("Bind done");
while (s != 0) {
if (listen(s, 1) != -1)
{
printf("Listening is successful.");
}
socklen_t size = sizeof(client_information);
new_socket = accept(s, (struct sockaddr*)&client_information, &size);
if (new_socket == -1)
{
printf("Accept failed");
return -2;
}
else
puts("Connection accepted");
for (;;) {
int res = recv(new_socket, buf, SERVER_BUF, 0);
printf("amount of bytes received:%d\n", res);
puts(buf);
fgets(gbuf, G_BUF, stdin);
send(new_socket, gbuf,strlen(gbuf)+1, 0);
if (strcmp(buf, "exit") == SAME)
break;
}
}
return 0;
}
【问题讨论】:
-
我在代码上尝试了一些东西,我意识到问题是这样的,但我无法解决。
-
一个包含语句,"#include "ws2_32.h" 被编译器(技术上是预处理器)用来将包含的文件的内容添加到你的源代码中。你需要做的第一件事要做的是确定“ws2_32.h”在您的系统上的位置。接下来,您需要将路径传递给编译器,以便它可以找到文件。在命令行上,它看起来像 'gcc -I c:\user \include' - 您必须将路径替换为系统上的路径。我从未使用过codelite,所以我不知道您在哪里输入该信息。
-
Windows SDK 与微软的编译器兼容。如果你使用不同的编译器,你就得靠自己了。无论如何,关键是,不要“撞”一个问题,重新问一遍基本上相同的问题。这不是 Stack Overflow 的工作方式。
-
简单的答案是删除试图包含它的行。你为什么相信它存在,你希望从中包含什么?有一个 ws2_32.lib 但据我所知,该库的标题是 WinSock2.h 和 WS2tcpip.h。
-
好的,谢谢。我写这个是因为据我研究这个库是 sockaddr 等代码所必需的。我的编译器没有识别出来。