qt udptcp 绑定发送源端口(Specify source UDP port when writing datagram)

xiaoxiao2021-02-28  92

在用qt发送udp协议的时候经常不仅仅需要制定接受端的端口,为了后续的处理还需要指定发送方的端口。通常我们使用udp写一个发送的数据的程序,使用如下的代码:

QUdpSocket *client = new QUdpSocket(this); client->open(QIODevice::ReadWrite); client->connectToHost(hostIp, portNumber); char charStore[500] = {0x82,0x23,0x05}; client->write(charStore,500);

上面的代码可以将数据发送到IP地址为hostIp的端口号为portNumber的地方去,我们通过wireshark抓包可以看到如下:

通过抓包可以看到此种情况下,发送端的端口为52276,是一个随机的数值,为了可以设定源端口使用如下代码:

QUdpSocket *client = new QUdpSocket(this); client->open(QIODevice::ReadWrite); client->bind(sourcePort); char charStore[500] = {0x82,0x23,0x05}; client->writeDatagram(charStore,500,hostIP,portNumber);

上面的代码可以将通过端口号为sourcePort将数据发送到IP地址为hostIp的端口号为portNumber的地方去,我们通过wireshark抓包可以看到如下:

通过抓包可以看到此种情况下,发送端的端口为5201,是设定的数值。

参考文献连接

转载请注明原文地址: https://www.6miu.com/read-63670.html

最新回复(0)