原创

UDP发广播给所有网卡(包含虚拟网卡)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://shazhenyu.blog.csdn.net/article/details/53607593
//给所有网卡发广播
QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
foreach (QNetworkInterface interface, networkinterfaces)
{
    foreach (QNetworkAddressEntry entry, interface.addressEntries())
    {
        QHostAddress broadcastAddress = entry.broadcast();
        if (broadcastAddress != QHostAddress::Null
              && entry.ip() != QHostAddress::LocalHost
              && entry.ip().protocol() == QAbstractSocket::IPv4Protocol
            )
        {
            udpSocketServer.writeDatagram(datagram, broadcastAddress, 13999);  // UDP 发送数据
         }
     }
}

UDP简单的使用:http://blog.csdn.net/u014597198/article/details/53509011

可以把其中的onServerSendBroadcast()函数用以下函数替换一下,就可以给机器内所有网卡发广播了

void UDPServerAndClient::onServerSendBroadcast()
{
    QByteArray datagram;
    QDataStream out(&datagram, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_6);
    out << QDateTime::currentDateTime() << QHostInfo::fromName(QHostInfo::localHostName()).addresses().last().toString();
    
  //给所有网卡发广播
    QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interface, networkinterfaces)
    {
    	foreach (QNetworkAddressEntry entry, interface.addressEntries())
    	{
        	QHostAddress broadcastAddress = entry.broadcast();
        	if (broadcastAddress != QHostAddress::Null
              	&& entry.ip() != QHostAddress::LocalHost
              	&& entry.ip().protocol() == QAbstractSocket::IPv4Protocol
            	)
        	{
            		udpSocketServer.writeDatagram(datagram, broadcastAddress, 13999);  // UDP 发送数据
         	}
     	}
     }
}

                                    
文章最后发布于: 2016-12-13 11:33:59
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览