Qt网络广播问题:获取发送者IP
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在读取数据包时检索发送者的 IP 地址 QUdpSocket::readDatagram()< /a>.您需要向 readDatagram() 传递一个指向 QHostAddress 的指针,用于在其中存储地址:
如果需要,您可以从 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:
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).
来自文档:
因此,如果您调用了
connectToHost()
,您应该会得到一个结果。您也可以尝试 peerAddress()。除非您始终通过名称进行连接,否则我不希望您始终能够进行反向查找并获取名称。From the docs:
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.