在局域網的開發過程中,有時候會用到通過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());
_BroadcastSock->readDatagram(datagram.data(), datagram.size(),&addr, &port);
QString ipStr(datagram);
BroadMsgHandle(addr,port,ipStr);
return;
}
}
在這裏獲取數據的 時候,同時把數據源的ip和端口都獲取了。QHostAddressaddr;quint16port;
具體協議如何實現,樓主是在
BroadMsgHandle(addr,port,ipStr);
中實現的。