0

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?

4

2 回答 2

1

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.

于 2012-07-17T06:24:54.487 回答
0

From the manual page of readDatagram:

qint64 QUdpSocket::readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 )

Receives a datagram no larger than maxSize bytes and stores it in data.
The sender's host address and port is stored in *address and *port
(unless the pointers are 0).

To receive a datagram you must first bind the socket to a specific UDP port. Then to get the source port of received datagrams you supply a non-zero parameter for the port argument of readDatagram.

于 2012-07-17T09:05:04.017 回答