Home > database >  Cannot create a socket in QT in windows
Cannot create a socket in QT in windows

Time:12-12

I am trying to open a socket in QT Creator and it compiles successfully but returns -1 when calling socket function (fails to create the socket).

I am using the following code:

#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

I have tried the following:

  1. Added QT -= gui core network instead of QT -= gui
  2. Used a hotspot instead of the WiFi [Thought it could be a problem with the network]
  3. Allowed the app to use private and public network from firewall: enter image description here
  4. Cleaned the project before rebuilding

CodePudding user response:

I was not calling WSAStartup. The following code is working.

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

CodePudding user response:

use QUdpSocket, add QT = network to *.pro file, using Qt Embedded Classes has more Cross Compile capibility

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