使用 Qt 读取 Colaso​​ft Packet Player 发送的网络数据

Read network-data send by Colasoft Packet Player with Qt

我正在尝试通过 Qt 读取 Colaso​​ft Packet Player 发送的数据。

我使用 IP 为 192.168.1.99 的环回适配器,Wireshark 显示如下:

来源IP: 192.168.1.1

源端口:40102

目标IP:224.0.1.12

目标端口:49156

但是使用这些 IP 和端口,Qt QUdpSocket 不显示任何数据。 当我尝试读取我接收数据的所有端口和 IP 时,程序应该可以工作,但似乎,我没有收到 Colaso​​ft Packet Player 发送的任何数据。

我做错了什么?

谢谢!

MyUDPSocket::MyUDPSocket(QObject *parent)
: QObject(parent)
{
    socket = new QUdpSocket(this);


    //socket->bind(QHostAddress("127.0.0.1"), 40102);
    //socket->bind(QHostAddress("127.0.0.1"), 49156);

    //socket->bind(QHostAddress("224.0.1.12"), 40102);
    //socket->bind(QHostAddress("224.0.1.12"), 49156);

    //socket->bind(QHostAddress("192.168.1.1"), 40102);
    //socket->bind(QHostAddress("192.168.1.1"), 49156);

    //socket->bind(QHostAddress("192.168.1.99"), 40102);
    //socket->bind(QHostAddress("192.168.1.99"), 49156);


    //socket->bind(QHostAddress::Any, 40102);
    //socket->bind(QHostAddress::Any, 49156);

    socket->bind(QHostAddress::Any, 49156, QUdpSocket::ShareAddress);   
    socket->joinMulticastGroup(QHostAddress("224.0.1.12"));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
}

void MyUDPSocket::readyRead()
{
        // when data comes in
        QByteArray buffer;
        buffer.resize(socket->pendingDatagramSize());

        QHostAddress sender;
        quint16 senderPort;

        // qint64 QUdpSocket::readDatagram(char * data, qint64 maxSize, 
        //                 QHostAddress * address = 0, quint16 * port = 0)
        // Receives a datagram no larger than maxSize bytes and stores it in data. 
        // The sender's host address and port is stored in *address and *port 
        // (unless the pointers are 0).

        socket->readDatagram(buffer.data(), buffer.size(),
                             &sender, &senderPort);
        qDebug() << "\n+-------------------------------";
        qDebug() << "|Message from:" << sender.toString(); 
        qDebug() << "|Message port:" << senderPort;
        qDebug() << "|Message:" << buffer;
        qDebug() << "+-------------------------------\n";
    }
}

地址224.0.1.12对应多播。 所以,您想加入多播流,请参阅 bool QUdpSocket::joinMulticastGroup(const QHostAddress & groupAddress),来自该文档:

Note that if you are attempting to join an IPv4 group, your socket must not be bound using IPv6 (or in dual mode, using QHostAddress::Any). You must use QHostAddress::AnyIPv4 instead.

还有QtMulticast Receiver Example.


由于原始问题代码更改而更新

我验证了编辑前的原始代码(没有 joinMulticastGroup())能够接收到端口 49156 的正常单播 UDP 数据包。因此,该代码用作服务器侦听绑定端口。

现在使用 joinMulticastGroup() 和替换 QHostAddress::Any -> QHostAddress::AnyIPv4 代码能够从 VLC 播放器接收多播流。

这样,编码问题就解决了。其他可能的问题:

  • 路由设置
  • Colaso​​ft Packet Player 打包的格式不正确