c++qtnetwork-programmingqudpsocket

How do I know the sending port number in QUdpSocket?


Is there a way I can get the port number the udp socket used to send message?

What I want to do is to send a udp datagram to someone and listen to that sending port.

For example in the following code:

QUdpSocket *s = new QUdpSocket(this);
s.writeDataGram(theData,theIp,thePort);

does it automaticly binds socket s with whatever the sending port is?

If so, can I listen to that sending port?


Solution

  • It would be safe to bind the socket to a port, address and specify the BindMode before sending data.

    Once a socket is bound to a port and address, readyRead() is emitted upon arrival of UDP Datagram at the specified port.

    So you can capture the readyRead() signal and process the data accordingly, ie you don't need to listen to the port. If you don't bind the socket s to the port thePort, readyRead() signal won't be emitted upon arrival of UDP Datagram.