无法在 windows 中的 QT 中创建套接字

Cannot create a socket in QT in windows

我正在尝试在 QT Creator 中打开一个套接字并且它编译成功但是 returns -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

我试过以下方法:

  1. 添加了 QT -= gui core network 而不是 QT -= gui
  2. 使用热点而不是 WiFi [认为可能是网络问题]
  3. 允许应用程序使用来自防火墙的私有和 public 网络:
  4. 重建前清理项目

我没有打电话给 WSAStartup。以下代码正在运行。

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>   // Needed for _wtoi

int main()
{
    WSADATA wsaData = {0};
    int iResult = 0;
    SOCKET sockfd;

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if ( sockfd == INVALID_SOCKET ) {
            perror("socket creation failed");
            exit(EXIT_FAILURE);
    }else{
        printf("Succeeded\n");
    }
    return 0;
}

使用QUdpSocket,在*.pro文件中添加QT += network, 使用 Qt Embedded 类 具有更多的交叉编译能力

void Server::initSocket()
{
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::LocalHost, 7755);

    connect(udpSocket, &QUdpSocket::readyRead, this, &Server::readPendingDatagrams);
}

void Server::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) 
    {
        QNetworkDatagram datagram = udpSocket->receiveDatagram();
        processTheDatagram(datagram);
    }
}