문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top