1
votes
Qt Version 5.10.0 (MSVC 2015, 32bit)

I have a PC which has a static host address("192.168.0.106"), and a device with an arbitrary IP address assigned by a router. I want to establish a UDP connection between them.

Qt has a udp demo called multicastreceiver, I modified the Receiver::processPendingDatagrams() function as followed:

QByteArray datagram;
QHostAddress senderIP = QHostAddress();
quint16 portx = 0;

while (udpSocket.hasPendingDatagrams()) {
    datagram.resize(int(udpSocket.pendingDatagramSize()));
    udpSocket.readDatagram(datagram.data(), datagram.size(), &senderIP, &portx);
    statusLabel->setText(tr("Received datagram: \"%1\" @ %2:%3")
        .arg(datagram.constData())
        .arg(senderIP.toIPv4Address())
        .arg(portx));
}

and in the construction function:

udpSocket.bind(QHostAddress::AnyIPv4, 18427, QUdpSocket::ShareAddress);
connect(&udpSocket, SIGNAL(readyRead()),
    this, SLOT(processPendingDatagrams()));

I successfully received the udp message, but

senderIP.toIPv4Address() is 0, and senderIP.toString is NULL
portx is 64800 but it is wrong

Could anyone please tell me what is wrong with these codes?

PS: I can get udp message and sender IP address and the right port number via a UDP debug tool(a PC program).

1
Try with QNetworkDatagram receiveDatagram() instead. Your code has some code smell due to manual buffer management etc. It's much easier to use QNetworkDatagram: it has all the data you desire.Kuba hasn't forgotten Monica

1 Answers

1
votes

I think you've found a known bug in Qt:

https://bugreports.qt.io/browse/QTBUG-64784

This is fixed in Qt 5.9.4 - and I believe in 5.10.1 also.

See also the commit.