Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send and receive UDP packets in QT

Tags:

networking

qt

udp

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.

like image 719
zuwgap Avatar asked Jun 29 '11 03:06

zuwgap


3 Answers

You're binding your udpSocketSend in QIODevice::ReadWrite mode. So that's the object that's going to be receiving the datagrams.

Try one of:

  • binding the send socket in write only mode, and the receive one in receive only mode
  • using the same socket for both purposes (remove udpSocketGet entirely).

depending on your constraints.

like image 39
Mat Avatar answered Oct 02 '22 10:10

Mat


I solved the problem. Here is the solution.

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

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

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

The device on the network listens on port 65001 and responds to packets on the source port of the received packet. It is necessary to use connectToHost(...) in order to know what port to bind for the response packet.

It is also necessary to bind to the correct address and port to receive the packets. This was the problem.

like image 60
zuwgap Avatar answered Oct 02 '22 08:10

zuwgap


For me, changing the bind from

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

to simple

udpSocket->bind(45454);

does the trick!

like image 38
Stadler Avatar answered Oct 02 '22 09:10

Stadler