提问人:User010000100110100101110010 提问时间:5/5/2023 最后编辑:User010000100110100101110010 更新时间:5/7/2023 访问量:56
在读取标头并找出数据包长度后,如何正确遍历数据包?
How do I correctly traverse through packets after reading the header and finding out the packetlength?
问:
给定此标头格式:
我正在尝试遍历并打印长度和数量市场更新:
std::ifstream fileOpener(m_rawInputFileName, std::ios::binary);
if (!fileOpener.is_open())
{
std::cout << "Error: could not open file" << std::endl;
fileOpener.close();
return;
}
short int packetLength;
short int numOfMarketUpdates;
while (fileOpener.read((char *)&packetLength, 2) &&
fileOpener.read((char *)&numOfMarketUpdates, 2))
{
cout << packetLength << ":" << numOfMarketUpdates << endl;
fileOpener.seekg(-4, std::ios::cur);
fileOpener.seekg(packetLength, std::ios::cur);
}
我做错了什么,还是数据不准确?
答:
0赞
User010000100110100101110010
5/7/2023
#1
答:我遗漏了一个重要的细节:“所有数据都按网络字节顺序排列。 因此,正确的代码是:
#include <arpa/inet.h>
std::ifstream fileOpener(m_rawInputFileName, std::ios::binary);
if (!fileOpener.is_open())
{
std::cout << "Error: could not open file" << std::endl;
return;
}
short int packetLength;
short int numOfMarketUpdates;
while (fileOpener.read((char *)&packetLength, 2) &&
fileOpener.read((char *)&numOfMarketUpdates, 2))
{
packetLength = nthos(packetLength);
numOfMarketUpdates = nthos(numOfMarketUpdates);
cout << packetLength << ":" << numOfMarketUpdates << endl;
fileOpener.seekg(-4, std::ios::cur);
fileOpener.seekg(packetLength, std::ios::cur);
}
nthos 将网络字节顺序转换为主机字节顺序。网络字节顺序配置为大端序,这可能与您的主机字节顺序不同,因此除非您将其转换为主机字节顺序,否则它没有意义。
感谢 user253751 指出这一点。
评论
fileOpener.seekg(packetLength - 4, std::ios::cur);
short int
int16_t
ntohs
cout << ntohs(packetLength) << ":" << ntohs(numOfMarketUpdates) << endl;