【问题标题】:Cannot create a socket in QT in windows无法在 Windows 的 QT 中创建套接字
【发布时间】: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

我尝试了以下方法:

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

【问题讨论】:

  • 实际的错误是什么?这与 Qt 有什么关系 - 您的示例中没有一行 Qt 代码。仅仅因为您使用的是使用 Qt 制作的 IDE?
  • 什么不起作用?
  • 请比“不能”更具体。它不编译,不运行,运行并崩溃,运行但打印错误消息,还是其他?
  • 请注意,perror 在printf 之后不一定有意义。在调用任何系统函数之前,您应该使用perror 或保存errno。
  • 我在这里看到 3 个潜在问题:没有执行 win sock 初始化(WSAStartup 必须在任何其他套接字 api 调用之前调用)和 socket 返回值可能会从 UINT_PTR 截断, 错误处理也是错误的,因为WSAGetLastError 没有被立即调用。

标签: c++ qt sockets firewall


【解决方案1】:

我没有打电话给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;
}

【讨论】:

    【解决方案2】:

    使用 QUdpSocket,将 QT += 网络添加到 *.pro 文件中, 使用 Qt Embedded Classes 具有更多的交叉编译能力

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2022-01-18
      • 2017-09-10
      • 2015-06-06
      • 1970-01-01
      • 2011-08-06
      相关资源
      最近更新 更多