在局域网的开发过程中,有时候会用到通过UDP广播去发现网段内的网段,可以采取这种方式:
_BroadcastSock = new QUdpSocket(this);
_BroadcastSock->bind(9090);
connect(_BroadcastSock,SIGNAL(readyRead()),this,SLOT(OnBroadcaseReceive()));
QByteArray cmd("GETIP");
cmd.push_back(0x0D);
cmd.push_back(0x0A);
if(_BroadcastSock->writeDatagram(cmd,cmd.length(),QHostAddress::Broadcast,9090) \
!=cmd.length())
{
QMessageBox::warning(this,tr("警告"),tr("网络错误"),0,0);
return;
}
绑定了端口后,当网段内其他IP在此端口发送数据,并且收到的时候,都会在OnBroadcaseReceive()槽函数中处理。
void smartclass::OnBroadcaseReceive()
{
QHostAddress addr;
quint16 port;
while (_BroadcastSock->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(_BroadcastSock->pendingDatagramSize());
_