QT之加入组播与广播

void Myudp::initSlot(QString ip,uint port)
{
    qDebug()<<ip<<port;
    udp = new QUdpSocket();
    if(!udp->bind(QHostAddress::AnyIPv4,port,QAbstractSocket::ShareAddress))
    {return;
    }
    else
    {
        bool ok = false;
        QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); //获取所有的网络接口
        foreach (QNetworkInterface intf, list) {    //遍历所有接口
            foreach (QNetworkAddressEntry entry, intf.addressEntries()) { // 遍历每个网卡
                if(entry.broadcast() != QHostAddress::Null && entry.ip()!= QHostAddress::LocalHost
                        && entry.ip().protocol() == QAbstractSocket::IPv4Protocol){
                    if(QHostAddress(ip) == entry.ip()){
                        udp->setMulticastInterface(intf);  //设置组播网卡
                        ok = true;
                        qDebug() << "bind udp successful!" << ok;
                        bool result = udp->joinMulticastGroup(QHostAddress("224.0.0.1"),intf); //加入组播
                        qDebug() << result;
                        udp->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption,1024*1024*8);  //设置缓冲区
                        break;
                    }
                }
            }
        }
        qDebug() << "xxxxxxx"<<ok;
    }
    QObject::connect(udp,SIGNAL(readyRead()),this,SLOT(rcvDataSlot()));
}

 二、广播。

udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, 45454);即可实现广播发送.  
bind(45454, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) //接收方

 

posted on 2021-01-29 16:11  缘随风烬  阅读(1026)  评论(0编辑  收藏  举报