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

//给所有网卡发广播
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 发送数据
         	}
     	}
     }
}

                                    
展开阅读全文
©️2020 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值