开发者

Qt Network Broadcasting Question: To get sender IP

开发者 https://www.devze.com 2023-03-02 04:00 出处:网络
There is a simple example about network broadcasting in QtSDK. It is easy to send and receive br开发者_StackOverflow中文版oadcast information. And in the receiver side, I want to know whose broadcast

There is a simple example about network broadcasting in QtSDK. It is easy to send and receive br开发者_StackOverflow中文版oadcast information. And in the receiver side, I want to know whose broadcast packet I just received. I try QUdpSocket.peerName() in readyRead signal callback function,but I get empty string. Any clue?


You can retrieve the sender's IP address when reading the packet with QUdpSocket::readDatagram(). You need to pass to readDatagram() a pointer to a QHostAddress in which to store the address:

QHostAddress senderAddress;
yourSocket->readDatagram(&data, size, &senderAddress);
// senderAddress now represents the sender address

You can get the address as a QString or integer from senderAddress if you need to, see the documentation for QHostAddress.

If you want a host name, you can use QHostInfo to do a reverse lookup (but you are not guaranteed to get a name).


From the docs:

Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.

So, if you've called connectToHost() you should get a result. You might also try peerAddress(). Unless you always connect via a name, I wouldn't expect that you'll always be able to do a reverse lookup and get a name.

0

精彩评论

暂无评论...
验证码 换一张
取 消