我試圖在 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 -= gui core network而不是QT -= gui - 使用熱點而不是 WiFi [認為可能是網路問題]
- 允許應用程式從防火墻使用私有和公共網路:

- 重建前清理專案
uj5u.com熱心網友回復:
我不是在打電話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;
}
uj5u.com熱心網友回復:
使用QUdpSocket,在*.pro檔案中添加QT = network,使用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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379728.html
