【发布时间】:2022-01-13 06:34:43
【问题描述】:
我正在尝试在 QT Creator 中打开一个套接字,它编译成功,但在调用套接字函数时返回 -1(创建套接字失败)。
我正在使用以下代码:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
printf("Code: %d\n", sockfd );
// Creating socket file descriptor
if ( sockfd == INVALID_SOCKET ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
return 0;
}
ServerAndClient.pro:
QT -= gui core network
CONFIG += c++11 console
CONFIG -= app_bundle
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
LIBS += -lws2_32
我尝试了以下方法:
【问题讨论】:
-
实际的错误是什么?这与 Qt 有什么关系 - 您的示例中没有一行 Qt 代码。仅仅因为您使用的是使用 Qt 制作的 IDE?
-
什么不起作用?
-
请比“不能”更具体。它不编译,不运行,运行并崩溃,运行但打印错误消息,还是其他?
-
请注意,
perror在printf之后不一定有意义。在调用任何系统函数之前,您应该使用perror或保存errno。 -
我在这里看到 3 个潜在问题:没有执行 win sock 初始化(
WSAStartup必须在任何其他套接字 api 调用之前调用)和socket返回值可能会从UINT_PTR截断, 错误处理也是错误的,因为WSAGetLastError没有被立即调用。