Qt网络广播问题:获取发送者IP

发布于 2024-11-04 19:16:32 字数 121 浏览 1 评论 0原文

QtSDK中有一个关于网络广播的简单例子。发送和接收广播信息很容易。而在接收端,我想知道我刚刚收到了谁的广播包。我在readyRead信号回调函数中尝试QUdpSocket.peerName(),但我得到空字符串。有什么线索吗?

There is a simple example about network broadcasting in QtSDK. It is easy to send and receive broadcast 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哆啦不做梦 2024-11-11 19:16:32

您可以在读取数据包时检索发送者的 IP 地址 QUdpSocket::readDatagram()< /a>.您需要向 readDatagram() 传递一个指向 QHostAddress 的指针,用于在其中存储地址:

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

如果需要,您可以从 senderAddress 获取 QString 或整数形式的地址,请参阅 QHostAddress

如果您想要主机名,可以使用 QHostInfo 进行反向查找(但不保证你能得到一个名字)。

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).

单身情人 2024-11-11 19:16:32

来自文档:

返回 connectToHost() 指定的对等点名称,如果尚未调用 connectToHost(),则返回空 QString。

因此,如果您调用了 connectToHost(),您应该会得到一个结果。您也可以尝试 peerAddress()。除非您始终通过名称进行连接,否则我不希望您始终能够进行反向查找并获取名称。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文