我正在从套接字读取数据并将接收到的数据从数据报发送到 HostMessage。但是当我尝试显示 HostMessage->MessageHeader 时,它显示无效数据。根据wireshark输出,数据报输出看起来也有点不同。
我通过ntonl函数解决了这个问题(并应用于MessageHeader,而不是所有数据报!!),b是正确的结果。使用此解决方案,我必须将 ntonl 应用于所有结构成员,并且我的成员超过 100 个。
您有解决此问题的任何解决方案或想法吗?
代码:
unsigned int ntonl(unsigned int a){
unsigned int b;
char* pA = (char*)&a;
char* pB = (char*)&b;
for (int i = 0; i < sizeof(pA); i++){
pB[i] = pA[(sizeof(pA)-1) - i];
}
return b;
}
void myDevice::processPendingDatagrams(){
while (m_udpSocket->hasPendingDatagrams()){
QByteArray datagram;
datagram.resize(m_udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
qint64 dataReceivedLength = m_udpSocket->readDatagram(datagram.data(),
datagram.size(),
&sender,
&senderPort);
tagHostMessage* HostMessage = (tagHostMessage*)datagram.data();
qDebug("datagram: %x-%x-%x-%x", datagram.data()[0], datagram.data()[1], datagram.data()[2], datagram.data()[3]);
qDebug()<<"msg header: " << HostMessage->MessageHeader[0] << "=" << HostMessage->MessageHeader;
b = ntonl(HostMessage->MessageHeader[0])
}
我的结构:
typedef struct tagHostMessage{
unsigned int MessageHeader[4];
TMessageData MessageData;
short int CheckSum;
}THostMessage,*PHostMessage;
Wireshark 输出(1024 字节):
0d:cc:97:e0:00:00:00:00:00:00:00:00:00:....
qDebug 输出:
datagram: d-ffffffcc-ffffff97-ffffffe0
msg header: 3768044557 = 0x9be9b8
a = e097cc0d
b = 0dcc97e0