How do I send and receive UDP packets in QT

Viewed 32038

I am writing a small application in QT that sends a UDP packet broadcast over the local network and waits for a UDP responce packet from one or more devices over the network.

Creating the sockets and sending the broadcast packet.

udpSocketSend = new QUdpSocket(this);
udpSocketGet  = new QUdpSocket(this);
bcast = new QHostAddress("192.168.1.255");

udpSocketSend->connectToHost(*bcast,65001,QIODevice::ReadWrite);
udpSocketGet->bind(udpSocketSend->localPort());
connect(udpSocketGet,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));

QByteArray *datagram = makeNewDatagram(); // data from external function
udpSocketSend->write(*datagram);

The application sends the packet properly and the response packet arrives but the readPendingDatagrams() function is never called. I have verified the packets are sent and received using Wireshark and that the application is listening on the port indicated in wireshark using Process Explorer.

3 Answers

For me, changing the bind from

udpSocket->bind(QHostAddress::LocalHost, 45454);

to simple

udpSocket->bind(45454);

does the trick!

Related