Solved can not get the sender's IP with UdpSocket
-
hi, any reader.
i am develop a udpsocket app on the win7 with Qt5.9.3 mingw.
this app will send some data to the local network to find some embed linux device by udp and IPv4, the socket code as below:
QUdpSocket *socket=new QUdpSocket(this);
socket->open(QIODevice::ReadWrite);
QHostAddress ad=QHostAddress(myIp);
socket->bind(ad,port,QUdpSocket::ShareAddress|QAbstractSocket::ReuseAddressHint);//Send data:
QHostAddress ad=QHostAddress(QHostAddress::Broadcast);
QByteArray dat=QByteArray("Hello");
socket->writeDatagram(dat.data(),dat.size(),ad,port);//Recv data:
QHostAddress sndIp;
quint16 uRcvPort;
while(socket->hasPendingDatagrams()){
qint64 l=recver->pendingDatagramSize();
socket->readDatagram(dat.data(),l,&sndIp,&uRcvPort);
}but the readDatagram do not fill any IP to the sndIp, the sndIp is NULL.
but, if i change the bind to :socket->bind(port,QUdpSocket::ShareAddress|QAbstractSocket::ReuseAddressHint);
the readDatagram will fill the sender's IP to the sndIP well.have any suggest for the QUdpSocket on the win7 64bits?
thanks.
-
@RunThiner you are blocking the event loop with your
while()
loop.Use proper signals&slots to react on incoming datagrams.
-
I was found an other way to solved this problem: use the receiveDatagram, it will get the sender's IP back well:
//recv data:
QNetworkDatagram nDat=socket->receiveDatagram(socket->pendingDatagramSize());
QHostaddress sndIp=nDat.senderAddress();i was tested on the ubuntu and win7,win10, the readDatagram and receiveDatagram can get the sender's IP on the ubuntu,
but the readDatagram do not get the sender's IP on the win7 and win10.
and the receiveDatagram can get the sender's IP on the win7 and win10. -
It is a bug. You can refer here
-
got it, thanks.
btw, i am test the QUdpSocket with QT5.12.0, the readDatagram does get the sender's ip back well.