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