【问题标题】:Qt QUdpSocket readDatagram cannot get sender IP addressQt QUdpSocket readDatagram无法获取发件人IP地址
【发布时间】:2018-09-08 04:02:28
【问题描述】:
Qt Version 5.10.0 (MSVC 2015, 32bit)

我有一台具有静态主机地址(“192.168.0.106”)的 PC,以及具有由路由器分配的任意 IP 地址的设备。我想在它们之间建立一个 UDP 连接。

Qt有一个udp demo叫做multicastreceiver,我修改了Receiver::processPendingDatagrams()函数如下:

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

在构造函数中:

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

我成功收到了udp消息,但是

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

谁能告诉我这些代码有什么问题?

PS:我可以通过 UDP 调试工具(PC 程序)获取 udp 消息和发送方 IP 地址以及正确的端口号。

【问题讨论】:

  • 尝试使用QNetworkDatagram receiveDatagram()。由于手动缓冲区管理等原因,您的代码有一些代码气味。使用QNetworkDatagram 更容易:它拥有您想要的所有数据。

标签: qt udp ip


【解决方案1】:

我认为您在 Qt 中发现了一个已知错误:

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

这在 Qt 5.9.4 中已修复 - 我也相信 5.10.1。

另见the commit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 2012-11-29
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2014-03-22
    相关资源
    最近更新 更多